目标:我在 Visual Studio 2022 中使用 C 语言,将位于 C:/Users/13383/Desktop/storage.txt 的文件中“STORAGE_”之后的序列号减少 7252。 storage.txt中的数据如下图:
...
"STORAGE_7253":
...
"STORAGE_7254":
...
"STORAGE_7255":
...
已经完成:我的程序如图:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1000
int main() {
FILE* fp;
char line[MAX_LINE_LENGTH];
char* pos;
int num;
if (fopen_s(&fp, "C:/Users/13383/Desktop/storage.txt", "r+") != 0) {
printf("Error opening file\n");
exit(1);
}
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
pos = strstr(line, "STORAGE_");
if (pos != NULL) {
num = atoi(pos + strlen("STORAGE_"));
printf("%d\n", num);
num -= 7252;
sprintf_s(pos + strlen("STORAGE_"), MAX_LINE_LENGTH - (pos - line) - strlen("STORAGE_"), "%d\"", num);
puts(line);
}
//fputs(line, fp);
}
fclose(fp);
printf("Done!\n");
return 0;
}
问题:当我注释掉
fputs(line, fp);
时,我发现变量“line”内容是正确的:
但是当我取消注释“fputs”以在文档中写入字符串时,提示错误:
所以我想知道问题是什么以及如何解决?
ps:我已经用python归档了这些代码,也许对有同样问题的人有帮助:
with open("C:/Users/13383/Desktop/storage.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for line in lines:
if "STORAGE_" in line:
num = int(line.split("STORAGE_")[1].split("\"")[0])
num -= 7252
line = line.replace(str(num + 7252), str(num))
f.write(line)
f.truncate()
print("Done!")
最简单的修复:
以只读方式打开“storage.txt”文件 - 我们将其称为 ifile
打开“new.storage.txt”文件进行输出 - 我们将其称为 ofile
从ifile进入读取循环
Read line from ifile
Process line
Write line to ofile
关闭i文件
关闭文件
如果新的文件创建成功,将ifile重命名为“yyyyMMddhhmmss.storage.txt”(其中“yyyyMMddhhmmss”代表日期时间)
将 offile 重命名为“storage.txt”
无损地更新文件总是最好的,因此编写新文件,然后重命名旧文件并重命名新文件是谨慎的方法。如果文件 I/O 操作期间出现问题,没有伤害,没有犯规。