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

标签 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”只是覆盖了自身。相反,我希望它而不是打印输出到文件.. 然后在新行中打印出新行。我使用正确吗?

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

yo.txt 中:

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

hi.txt中:

Please help me.

预期的最终结果:

Hello stackoverflow.
Please help me
Thank you!

最佳答案

当您进入下一个级别时,即

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

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

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

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

 void fileOpen(char * fname, FILE* output)

关于c - fprintf 没有按照我想要的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566296/

相关文章:

c - 如何修复calloc时的内存泄漏

c - 解析串口数据

c - 用 C 语言将文件压缩为运行长度代码的程序

string - Perl Text::CSV_XS 从字符串中读取

ruby - 当匹配正则表达式时从 Ruby 文件中删除字符串

c - 找出特定目录所在的文件系统大小和名称

php - 文件API上传文件

python - 为什么在 Python 中执行时不能将 printf 与 sqlite 一起使用

c - 请解释代码的输出

c - sprintf 不断返回相同的字符串