-1

楽しみのために、テキストファイルを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");

    }

誰かが私が間違っていることについて私にアドバイスできますか?

4

1 に答える 1

3

この行を修正する必要があります:

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

実際には、行から最大20文字を取得するため、行全体を読み取ることはありません。次に、行の残りの部分が次の反復で読み取られますが、「print」という単語が含まれていないため、スキップされます。このエラーを修正するには、1行あたり20文字を超える文字を取得する必要があります。バッファ(b)のサイズは1000なので、余裕があります。

于 2013-02-23T00:58:29.323 に答える