2013-02-23 50 views
-1

我想創建一個程序,將文本文件轉換爲c,只是爲了它的樂趣。我的問題是輸出值與它應該是不同的。C程序省略字符

#include <stdio.h> 
    #include <string.h> 

    int main(int argc, char *argv[]) { 


    FILE *intf=fopen(argv[1], "r");  //input and output file 
    FILE *ocf=fopen(argv[2], "w"); 
    char b[1000]; 
    char *d; 
    char *s; 
    char *token; 

    const char delim [2] = "`"; 

     fprintf(ocf, "#include <stdio.h>\n int main(void) {\n"); //Preparation 

    while (fgets(b, 20, intf) !=NULL) { //Ensure that EOF has not been reached 

     if (d = strstr(b, "print")) { //Search for "print" in the file 
      fprintf(ocf, "printf(\""); //Prepare for "printf("");" statement 
      s=strstr(b, "`");  //Search for delimiting character 
      token=strtok(s, delim);  //Omit delimiting character 
    while(token != NULL) { 
      token[strlen(token)-1]=NULL; //Omit newline character that kept geting inserted 
      fprintf(ocf, "%s", token); //Print what was read 
      token = strtok(NULL, delim); // 
    } 
     fprintf(ocf, "\");\n");  //Finish printf() statement 
    } 

    } 
     fprintf(ocf, "\n}");  //Finish c file 
     printf("Creation of c file complete \n"); 
    } 

輸入文件:

print `hello\n world 
    print `Have a nice day 

和輸出:

#include <stdio.h> 
    int main(void) { 
    printf("hello\n wor"); 
    printf("Have a nice"); 

    } 

有人能告訴我在我在做什麼錯誤?

+0

請修正您的代碼的縮進,使其更易於閱讀。 – 2013-02-23 00:50:19

回答

3

您應該解決這一行:

while (fgets(b, 20, intf) !=NULL) 

它實際上起身準備從行20個字符,所以你不讀整行。然後在下一次迭代中讀取該行的其餘部分,但由於它不包含單詞「print」,因此它會被跳過。您應該每行獲得超過20個字符來解決此錯誤。你的緩衝區(b)大小爲1000,所以你可以負擔得起。

+0

謝謝!這工作完美。我以爲我錯誤地使用了strtok。 – ikdevel 2013-02-23 01:01:16

+1

+1:發現您的診斷。 – 2013-02-23 01:02:07