【问题标题】:fprintf not working the way I want it tofprintf 没有按我想要的方式工作
【发布时间】:2023-03-15 23:10:01
【问题描述】:
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!

【问题讨论】:

  • 或许将'\n' 添加到fprintf
  • perror( fname ), perror( fname ), perror( fname )!!!!!如果我看到另一条错误消息未能告诉我该消息适用的文件的名称,我会尖叫。
  • 您正在以w 模式打开output.txt。每次执行此操作时,都会截断(丢弃)之前编写的所有内容。
  • 好吧,对于初学者来说,“#include”是 8 个字符。
  • 大声笑,很好,谢谢!

标签: c file printf


【解决方案1】:

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

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

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

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

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

 void fileOpen(char * fname, FILE* output)

【讨论】:

  • 为什么不简单地fopen("output.txt", "a");?应该可以解决问题(尽管在递归调用之前必须在某处擦除文件)。
  • 好的,有道理,谢谢。我创建了另一个返回 FILE 的函数来专门打开文件。我还有一个问题。 fcloseall() 在完成读取之前关闭所有文件(在递归堆栈上)。我可以在主函数中使用该命令吗?它还会关闭其他函数中的文件吗?
  • @juice:为什么不直接关闭你在函数中打开的文件?至少在 Windows 上,您可以拥有的“打开文件”的数量是最大的(顺便说一下,这将是一个问题,深度递归)。
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
相关资源
最近更新 更多