2017-05-17 11 views
-1

私は、異なる行の値を持つファイルをどのように読み込み、私がメモリに持っている値と比較して、より良いスコアを得るか知っておく必要があります。 (ファイルが読み込まとして開いており、このコードの一部は、同時に複数のフォーク()から実行される可能性があるので、同時に書き込み、など)ファイル:ファイルを読み込んでCの値を比較する方法は?

if (PuntuacioEquip(jugadors)>MaxPuntuacio && CostEquip(jugadors)<PresupostFitxatges) 
    { 

     //Compare with file 
     int fd, n; 
     TBestEquip info; 

     fd = open("best_teams.txt", O_RDONLY); 
     if (fd<0) panic("open"); 

     while ((n=read(fd, &info, sizeof(info))) == sizeof(info)) { 
      //printf(cad,"equip %lld, puntuacio %d\n", info.Equip, info.Puntuacio); 
      //write(1,cad,strlen(cad)); 
      if (info.Puntuacio>PuntuacioEquip(jugadors)) 
       { 
        fd = open("best_teams.txt", O_WRDONLY|O_TRUNC|O_CREAT,0600); 
        if (fd<0) panic("open"); 
        sprintf(cad,"%s Cost: %d Points: %d. %s\n", CostEquip(jugadors), PuntuacioEquip(jugadors)); 
        write(fd,cad,strlen(cad)); 
       } 
     } 


     // We have a new partial optimal team. 
     MaxPuntuacio=PuntuacioEquip(jugadors); 
     memcpy(MillorEquip,&jugadors,sizeof(TJugadorsEquip)); 
     sprintf(cad,"%s Cost: %d Points: %d. %s\n", color_green, CostEquip(jugadors), PuntuacioEquip(jugadors), end_color); 
     write(1,cad,strlen(cad)); 


    } 

は、任意の助けに感謝。

よろしく、

+1

スペイン語または英語の言語を選択することをお勧めします。この混合物は良い習慣ではないようです。 – arboreal84

+0

何が問題ですか? –

+1

別のファイルを更新している間に、あるファイルから読み込むことをお勧めします。終了したら、元のファイルを削除して新しいファイルの名前を変更します。 – Neil

答えて

0

ファイルを反復処理するための最良の方法は、関数getline()を使用することです。ここでは、その使用例をthis postから取っておきます。

char const* const fileName = "best_teams.txt" ; // 
FILE* file = fopen(fileName, "r"); /* should check the result */ 
if (file != NULL) { 

    char line[256]; 
    while (getline(line, sizeof(line), file)) { // Each iteration, a line will be stored in string `line` 
      // Do what you want to do 
    } // Exits when arrives at the end of the file 
else puts("Error while opening file\n"); 

コメントで示唆したように、あなたはその後、fopen("best_teams.txt", "w") を使用することができ、「W」はfopen documentationに従うと記載されているライトモード、意味:

は、書き込み用に空のファイルを作成しますが。同じ名前のファイルがすでに存在する場合、その内容は消去され、そのファイルは新しい空のファイルとみなされます。

もう1つの解決策は、読み書きモードで開き、必要な値だけを変更することですが、もっと複雑になる可能性があります。

+0

'getline()'とは何ですか?あなたのスニペットにはどこですか? –

+0

問題は、運動がすべきであるように、私は与えられた規則に従わなければならないということです。そして、これはオープン関数を使用することを意味します。 – llinasenc

+0

@FelixPalmenああ、ええ、すみません。固定 – Badda

関連する問題