我的程序中有一个函数必须从文件中删除给定的字符串。为此,请将整个文件重写为临时文件,然后覆盖原始文件。 使用删除的字符串保存临时文件可以,但覆盖原始文件不起作用。
这里出了什么问题?
#define MAXCHAR 10000
void delPath(char stringToDelete[], char bashrcDir[]) {
FILE *bashrc = fopen(bashrcDir, "r+");
char str[MAXCHAR];
if (bashrc != NULL) {
FILE *tempfile = fopen("./tempFile.txt", "w+");
// Create tempFile and copy content without given string
while (fgets(str, MAXCHAR, bashrc) != NULL) {
if (!strstr(str, stringToDelete)) {
fprintf(tempfile, "%s", str);
}
}
// Read tempFile and overwrite original file - this doesn't work
while (fgets(str, MAXCHAR, tempfile) != NULL) {
fprintf(bashrc, "%s", str);
}
fclose(tempfile);
}
fclose(bashrc);
}
r+ 允许您读取文件并覆盖它。我错了吗?
最佳答案
引用@KamilCuk 的回答,解决方案如下:
#define MAXCHAR 10000
void delPath(char stringToDelete[], char bashrcDir[]) {
FILE *bashrc = fopen(bashrcDir, "r");
char str[MAXCHAR];
if (bashrc != NULL) {
FILE *tempfile = fopen("./tempFile.txt", "w");
while (fgets(str, MAXCHAR, bashrc) != NULL) {
if (!strstr(str, stringToDelete)) {
fprintf(tempfile, "%s", str);
}
}
fclose(bashrc);
fclose(tempfile);
FILE *newTempfile = fopen("./tempFile.txt", "r");
FILE *newBashrc = fopen(bashrcDir, "w");
while (fgets(str, MAXCHAR, newTempfile) != NULL) {
fprintf(newBashrc, "%s", str);
}
fclose(newTempfile);
fclose(newBashrc);
remove("./tempFile.txt");
}
}
谢谢!
关于C 读取文件后无法写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59726763/