【发布时间】:2022-01-09 11:03:53
【问题描述】:
嗯,我在使用函数将字符串写入 txt 文件时遇到问题,我只是不明白为什么我不能打印字符串,当程序在函数中时它会停止工作。 这是创建通过引用文件传递值的函数的代码,它完美地工作:
void saveTXT(FILE** txt,char *string)
{
fputs(string,*txt);
}
int main()
{
FILE * doc;
char string [10], singleline[50];
printf("Write the name of the file: \n");
scanf("%s",string);
fflush(stdin);
printf("Write the string to save into the file:\n");
scanf("%[^\n]",singleline);
doc = fopen(string,"w");
saveTXT(&doc,singleline);
fclose(doc);
return 0;
}
但是当我回到具有相同逻辑的项目时,程序就会关闭:
void saveTXT(FILE** txt,node* n)
{
char buffer[100];
if(n == NULL)
fprintf(*txt,"*\n");
else
{
strcat(strcpy(buffer,n->data),"\n");
fflush(stdin);
printf("This is the string to be saved: %s\n",buffer);
fputs(buffer,*txt); //Problem
saveTXT(&(*txt),n->right);
saveTXT(&(*txt),n->left);
}
}
我确保之前打开文件然后关闭它,我打印的是要保存在文件中的字符串,它显示字符串然后崩溃,我只是不知道为什么会发生这种情况。
【问题讨论】:
-
请提供失败代码的minimal reproducible example。
node和guardarTXT是什么?这个函数是怎么调用的。使用前是否检查文件指针是否为 NULL? -
另外,在调试器中运行您的程序并告诉我们它在哪里崩溃。
-
我纠正了错误,这是一个递归函数,问题是当我使用 fputs() 时程序停止。并且我在这两种情况下都对程序进行了编译和调试。