【发布时间】:2015-06-21 11:28:30
【问题描述】:
我正在开发一个实用程序,它可以扫描多个文本文件、提取相关文本并将其转储到另一个文本文件中。
int main()
{
// file I/O code
node *temp1;
char script[255],segName[255],ch;
char *dev;
FILE *fp;
int i=0;
void removeSpace();
dev=getenv("DEVSET");
devset = atoi(dev);
//clearing the file before starting
fp=fopen("output.txt","w");
fclose(fp);
memset(script,'\0',sizeof(script));
strcpy(script,"main"); // start with main
head=createNode(script); // head is a global node*
head->prev=NULL;
head->next=NULL;
temp1 = head;
while(temp1 !=NULL)
{
read(temp1, script);// reads the text file corresponding to temp1 and returns relevant data
memset(segName,'\0',sizeof(segName));
if (strcmp((temp1->name),"main"))
{
//if not main, start on a new line
segName[0]='\n';
}
if (strcmp(script,"EOF")== 0 || strcmp(script,"")== 0 )
{
// end of file or Call not found
temp1 = pop(head);
}
else
{
if (strcmp(script,"exit_flow") == 0)
{
fp=fopen("output.txt","a");
fprintf(fp,"//FNF");
fclose(fp);
temp1=pop(head);
}
else
{
//Call found
for(i=0;i<script_index;i++) // script index is a global int
{
strcat(segName,"-"); // no of dashes indicate depth of the call
}
strcat(segName,"<");
i=strlen(segName);
segName[i]=call_type;
strcat(segName,">");
strcat(segName,(script));
fp=fopen("output.txt","a");
fprintf(fp,segName);
fclose(fp);
script_index++;
temp1=createNode(script);
push(head,temp1);
}
}
}// end of while
// Adjustment to remove extra spaces from the file
removeSpace();
fclose(fp);
if(!devset)
printf("\nExecution complete");
printf("\nResult dumped to \"output.txt\"");
printf("\nOpen the output file? ");
fflush(stdin);
ch=getchar();
if (ch == 'y' || ch == 'Y')
{
system("notepad output.txt");// Text file displayed has correct data here
}
return 0;
}
上面提到的是main()的一部分。
在执行 'system' 语句后,文件的内容被修改了多少看起来不太可能。 一个字符串(不是完全随机的)被附加到文本文件中,尽管我在执行“系统”之前关闭了文件。
环境 - 窗户
IDE-代码::块
编译器 - MinGW
这是因为我没有刷新一些缓冲区吗?
【问题讨论】:
-
有一个丢失代码的日志,并且在
stdin上执行fflush在技术上是未定义的行为。 -
发布的代码有多个问题,它不是偶然的真实代码,因为它永远不会编译,例如
fp声明在哪里?如果不是fopen()ed,你为什么要fclose()呢?而fflush(stdin)是未定义的行为。 -
“字符串(不完全随机)”是否给了你线索?
-
这不会编译。
ch未定义。 -
看,这就是为什么人们一直要求你发布一个最小的、完整的、可验证的例子。快速阅读,根据缩进,我认为您所询问的代码——
system(notepad)调用——是在名为 removeSpace 的函数中。当您发布此类误导性示例时,无法为您提供帮助。