【发布时间】:2017-04-16 11:12:32
【问题描述】:
我正在尝试从文本文件中删除特定字符串。我必须从文件 [Ipsum, printing] 中删除两个字符串。我首先尝试从文件中只删除第一个字符串。但是字符串不能被删除。我无法更正我的代码,我犯了错误。
#include <stdio.h>
#include <stdlib.h>
int main() {
int j = 0, i;
char getText[1000] = "Lorem Ipsum is simply dummy text of the printing and typesetting industry";
FILE * fptr, * fp2;
char a[1000], temp[1000];
char key[50] = "Ipsum", textDelete_2[50] = "printing";
fptr = fopen("D:\\test.txt", "w");
if (fptr == NULL) {
printf("File can not be opened. \n");
exit(0);
}
fputs(getText, fptr);
fp2 = fopen("D:\\temp.txt", "w");
if (fp2 == NULL) {
printf("File fp2 can not be opened. \n");
exit(0);
}
printf("\n processing ... \n");
while (fgets(a,1000,fptr)) {
for (i = 0; a[i] != '\0'; ++i) {
if (a[i] == ' ') {
temp[j] = 0;
if (strcmp(temp, key) != 0) {
fputs(temp, fp2);
}
j = 0;
fputs(" ", fp2);
} else {
temp[j++] = a[i];
}
}
if (strcmp(temp, key) != 0) {
fputs(temp, fp2);
}
fputs("\n", fp2);
a[0] = 0;
}
fclose(fptr);
fclose(fp2);
printf("\n processing completed");
return 0;
}
【问题讨论】:
-
strstr()和memmove()是你的朋友。 (但也可以复制到新字符串中) -
"w"-->"w+"。并执行fflush和rewind。