Cor*_*rey 7 c pointers file overwrite fgets
我有一个文本文件text.txt读取(为简单起见)
this is line one
this is line two
this is line three
Run Code Online (Sandbox Code Playgroud)
为了简单起见,我只是试图将每行中的第一个字符设置为'x',所以我想要的结果是
xhis is line one
xhis is line two
xhis is line three
Run Code Online (Sandbox Code Playgroud)
所以我打开text.txt文件并尝试用所需的输出覆盖每一行到同一文本文件.在while循环中,我将每行中的第一个字符设置为"x".我还将变量"line"设置为等于1,因为如果它在第一行,我想倒回到文件的开头,以便在开头而不是在文件末尾覆盖.然后增加行,以便在下一次迭代时跳过倒带,并且应该继续覆盖第2行和第3行.它适用于第一行.
有人有任何解决方案吗?顺便说一句,我已经在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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
xhis is line one
this is line two
xhis is line two
e
x
Run Code Online (Sandbox Code Playgroud)
long pos = ftell(fp);//Save the current position
while (fgets(buffer, 500, fp) != NULL) {
buffer[0] = 'x';
fseek(fp, pos, SEEK_SET);//move to beginning of line
fprintf(fp, "%s", buffer);
fflush(fp);
pos = ftell(fp);//Save the current position
}
Run Code Online (Sandbox Code Playgroud)