-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”。您应该每行获得超过 20 个字符来修复此错误。您的缓冲区 (b) 大小为 1000,因此您可以负担得起。

于 2013-02-23T00:58:29.323 回答