我有一个文本文件text.txt,内容如下(为了简单起见):
this is line one
this is line two
this is line three
为了简单起见,我只是尝试将每行的第一个字符设置为'x',所以我的期望结果将是:
xhis is line one
xhis is line two
xhis is line three
我正在打开text.txt文件并尝试覆盖同一文本文件中的每一行,我在while循环中将每一行的第一个字符设置为'x'。我还将变量"line"设置为1,因为如果它在第一行,我希望倒回到文件开头以便在文件开始处进行覆盖而不是在文件结尾处。然后递增line变量以跳过下次迭代的倒回操作,并应该继续覆盖第二和第三行。对于第一行效果很完美。
有人有什么解决方法吗?顺便说一下,我已经在stackoverflow和其他网站上进行了广泛的研究,但没有成功。以下是我的代码以及我的输出:
#include <stdio.h>
#include <stdlib.h>
#define MAX 500
int main() {
char *buffer = malloc(sizeof(char) * MAX);
FILE *fp = fopen("text.txt", "r+");
int line = 1;
while (fgets(buffer, 500, fp) != NULL) {
buffer[0] = 'x';
if (line == 1) {
rewind(fp);
fprintf(fp, "%s", buffer);
}
else {
fprintf(fp, "%s", buffer);
}
line++;
}
free(buffer);
fclose(fp);
}
输出:
xhis is line one
this is line two
xhis is line two
e
x
unlink(“text.txt”);
- 然后使用相同的名称打开一个新文件,并将修改后的行写入新文件。您将有两个FILE *
变量。 - Andrew Henlefseek(fp, 0, SEEK_CUR)
的东西。然后在完成写入后再次调用,在重新开始读取之前。 - Steve Summit