fprintf没有按照我想要的方式工作

时间:2013-10-24 12:43:14

标签: c file printf

void fileOpen(char * fname)
{
    FILE *txt, *newTxt;
    char line[256];
    char fileName[256];

    txt = fopen(fname, "r");    
    if(txt == NULL)
    {
        perror("Error opening file");
        exit (EXIT_FAILURE);
    }

    newTxt = fopen("output.txt", "w");
    if(newTxt == NULL)
    {
        perror("Error opening file");
        exit(EXIT_FAILURE);
    }
    //Problem is in the while loop
    while(fgets(line, 256, txt) != NULL)
    {
        if (strncmp(line, "#include", 7) == 0)
        {   
            strcpy(fileName, extractSubstring(line));
            fileOpen(fileName);
        }

        else
            fprintf(newTxt, "%s", line); <---- It just prints over itself
    }

    fcloseall();
}

程序的重点是递归文件提取。每当它在行的开头看到#include时,它就会打印出文件的内容。

由于某些原因,在每一行中,变量“line”只是自我写入。相反,我希望它而不是打印输出到文件..然后在新行打印出新行。我正确使用它吗?

示例:我使用命令行参数yo.txt传递给void fileOpen(char *fname)

yo.txt

Hello stackoverflow.
#include "hi.txt"
Thank you!  

hi.txt

Please help me.

预期的最终结果:

Hello stackoverflow.
Please help me
Thank you!

1 个答案:

答案 0 :(得分:3)

当你进入下一个级别,即

strcpy(fileName, extractSubstring(line));
fileOpen(fileName);

再次打开相同的输出文件,

newTxt = fopen("output.txt", "w");

而是将文件指针作为fileOpen的函数参数传递给输出文件。在打开第一个文件之前,您应该打开输出文件并将其传递给fileOpen。​​

 void fileOpen(char * fname, FILE* output)