我正在尝试编辑txt文件中的第一行,但由于某种原因,它将用空格字符替换下一行...
int main()
{
FILE *myFile;
myFile = fopen("test.txt", "r+");
fprintf(myFile, "Hello\n");
fclose(myFile);
}
Run Code Online (Sandbox Code Playgroud)
运行代码前的txt文件:
i
like
this
Run Code Online (Sandbox Code Playgroud)
运行代码后的txt文件:
Hello
this
Run Code Online (Sandbox Code Playgroud)
小智 7
你的代码没有替换行,它是替换字节.你的字符串("Hello \n")是六个字节长.你文件的前六个字节是"我不喜欢".一旦你的代码执行了你就有了"Hello \n \nthis" - 即'Hello',两个换行符和'this'.
如果您只是尝试替换第一行,则需要读取整个文件,解析行,替换要替换的行,然后写出新内容.