【发布时间】: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 个字符。
-
大声笑,很好,谢谢!