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!