在C中编辑文件的特定行

时间:2013-05-30 15:37:58

标签: c file

我在C中遇到编辑文件特定行的问题。文件的开头有一个数字,后面跟着许多行。它有点像这样。

2
Nasif  20  BUET  130
Oishi  24  KMC  131

每次执行后,我在文件中再添加一行。并且文件中的第一个数字(实际上表示行数)增加1.此过程似乎不起作用。

data=fopen("highscore.txt","r");
fscanf(data,"%d",&number_of_scores);
fclose(data);
if(number_of_scores<10){
    data=fopen("highscore.txt","a");
    fprintf(data,"%s  %s  %s  %s\n", user[current_user].name,
            user[current_user].age, user[current_user].college,result);
    number_of_scores++;
    fseek(data,0,0);
    fprintf(data,"%d",number_of_scores);
    fclose(data);
}
else{

}

那么,什么应该是正确的方法?

4 个答案:

答案 0 :(得分:2)

对于fopen模式,请参阅http://www.cplusplus.com/reference/cstdio/fopen/。我认为您需要使用选项r+,因为您正在以随机访问的方式修改文件,无论是读取还是写入。

  

“r +”读取/更新:打开文件进行更新(包括输入和输出)。   该文件必须存在。

     

“w +”写入/更新:创建一个空文件并打开   它用于更新(输入和输出)。如果一个文件具有相同的   name已存在,其内容将被丢弃并处理该文件   作为一个新的空文件。

     

“a +”追加/更新:打开文件进行更新(两者都有   用于输入和输出)所有输出操作在数据处写入数据   文件的结尾。重新定位操作(fseek,fsetpos,rewind)   影响下一个输入操作,但输出操作会移动   位置回到文件的末尾。如果没有,则创建该文件   存在。

我建议将文件中的行数存储为无符号整数而不是字符串。原因是,作为字符串0-9行占用一个字节,但是你有10行的那一分钟你需要两个字节,100,3个字节,依此类推。在每种情况下,当需要额外的字符时,您将不得不重写整个文件。我认为这就是为什么你检查得分数小于10的原因。

更好的解决方案是将文件的前4个字节保留为无符号整数,然后在之后启动ascii文本。

int      result;
uint32_t number_of_scores;
size_t   bytesRead;
FILE     *data;

...

/* Open a file for update (both for input and output).
* The file must exist. */
data = fopen("highscore.txt","r+");
if( !data ) 
    exit(SOME_ERROR_CODE);

/* Read a 32-bit unsigned integer from the file. NOTE there is no endianess
 * "protection" here... ignoring this issue for the sake of simplicity and relevance */
bytesRead = fread (&number_of_scores, sizeof(number_of_scores), 1, data);   
if( bytesRead != 1 )
    exit(SOME_ERROR_CODE);

/* Seek to end of file */
result = fseek(data, 0, SEEK_END);    
if( result )
    exit(SOME_ERROR_CODE);

/* Write in the next line */
result = fprintf(data,
                 "%s  %s  %s  %s\n", 
                 user[current_user].name,
                 user[current_user].age, 
                 user[current_user].college,
                 resultVariableRenamedToAvoidNameCollision);

 /* Up the number of scores and write it back to the start of the file */
 number_of_scores++;
 result = fseek(data, 0, SEEK_SET);      
 if( result )
     exit(SOME_ERROR_CODE);

 bytesRead = fwrite (data, sizeof(number_of_scores), 1, data);
 if( bytesRead != 1 )
    exit(SOME_ERROR_CODE);

 fclose(data);

Doh,我刚刚意识到这个答案有多晚......没关系:S

答案 1 :(得分:1)

您需要以读写模式("r+")打开文件,而不是追加("a")。写入位置最初将位于开始位置,因此您最好先更新行数。然后,您可以在添加新行之前fseek(data, 0, SEEK_END)

答案 2 :(得分:0)

尝试在第二次"a"来电时将"w+"替换为fopen()"a"用于在文件末尾添加信息。 =)

编辑: 但是,我也会用一些固定的空格填充书写的数字,否则,当代码当前写入时,当计数超过9时,你可能会覆盖第一行的行尾标记。

答案 3 :(得分:0)

  1. 无需多次打开文件。
  2. 需要寻找准确点的文件指针。
  3. 如果必须读取文件中的数据,则必须以读取模式打开文件。