我正在尝试从文本文件中删除特定字符串。我要从文件[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;
}
答案 0 :(得分:1)
首先,您的输入文件以参数w
打开,代表write
,因此它将清除输入文件的内容,使输入无效。
此外,您的代码会在行结束之前或1000个字符结尾之前生成符号\ 0(如果您没有写完整行或1000个字符,它会将其余内容读作符号)。< / p>
最终代码
#include <stdio.h>
#include <stdlib.h>
int main() {
int j = 0, i;
FILE * fptr, * fp2;
char a[1024], temp[1024];
char *key = "THIS", *textDelete_2 = "IS";
fptr = fopen("test.txt", "r");
if (fptr == NULL) {
printf("File can not be opened. \n");
exit(0);
}
fp2 = fopen("temp.txt", "w");
if (fp2 == NULL) {
printf("File fp2 can not be opened. \n");
exit(0);
}
printf("\n processing ... \n");
while (fgets(a, sizeof(a), fptr)) {
for (i = 0; a[i] != '\0'; ++i) {
if (a[i] == 0)break;
if (a[i] == ' ') {
temp[j] = 0;
if (strcmp(temp, key) != 0) {
fputs(temp, fp2);
}
j = 0;
fputs(" ", fp2);
} else {
temp[j++] = a[i];
}
}
for (i = 0; i < strlen(temp); i++){
if (!isalpha(temp[i]))temp[i] = ' ';
}
if (strcmp(temp, key) != 0) {
fputs(temp, fp2);
}
fputs("\n", fp2);
a[0] = 0;
}
fclose(fptr);
fclose(fp2);
printf("\n processing completed");
getchar();
return 0;
}
输入:
THIS IS SPARTAAAAAAAAAAAAAA
输出:
IS SPARTAAAAAAAAAAAAAA