2017-04-16 96 views
-1

我想從文本文件中刪除特定的字符串。我必須從文件[Ipsum,打印]中刪除兩個字符串。我試着先刪除文件中的第一個字符串。但是字符串不能被刪除。我無法糾正我的代碼,我犯了錯誤。所有的從文本文件中刪除多個字符使用C

#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; 
    } 
+1

'的strstr()'和'的memmove()'是你的朋友。 (但是複製到一個新的字符串也會起作用) – wildplasser

+0

'「w」' - >'「w +」'。並做'fflush'和'rewind'。 – BLUEPIXY

回答

1

首先,輸入文件是與代表write的說法w開放的,所以它會清除輸入的文件使輸入無用的內容。

此外,如果在行尾之前或1000字符結束之前是\ 0(如果您沒有寫入整行或1000個字符,它會將其餘內容作爲符號讀取),您的代碼將生成符號。

最終代碼

#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 
+0

它爲一個字符串工作,但我怎樣才能從句子中刪除多個字符串。就像我要刪除這個和IS。我試圖修改你的代碼,但不能得到正確的結果。請幫忙!!! – nischalinn

+0

@nischalinn將while循環放入一個函數,請求參數「a」,然後調用它兩次(「a」是被刪除的字符串) –