gpt4 book ai didi

c - 在 C 中编辑文件的特定行

转载 作者:行者123 更新时间:2023-12-02 05:02:31 27 4
gpt4 key购买 nike

我在用 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{

}

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

最佳答案

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

"r+" read/update: Open a file for update (both for input and output). The file must exist.

"w+" write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.

"a+" append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

我建议将文件中的行数存储为无符号整数而不是字符串。原因是作为一个字符串,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);

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

关于c - 在 C 中编辑文件的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840323/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com