[英]Program crash when try to write into a file using a function by reference C
Well I have a problem using a function to write a string into a txt file, I just can't see why I can't print the string, when the program is in the function it just stop working.好吧,我在使用 function 将字符串写入 txt 文件时遇到问题,我只是不明白为什么我无法打印字符串,当程序在 function 中时它只是停止工作。 This is the code creating a function passing the value by reference of the file and it works perfectly:这是创建 function 通过引用文件传递值的代码,它完美地工作:
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;
}
But when I go back to my project that has the same logic the program just closes:但是当我 go 回到具有相同逻辑的项目时,程序就会关闭:
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);
}
}
I made sure to open the file before and close it later, what I print is the string to be saved in the file, it shows the string and then crash, I just don't know why that happens.我确保之前打开文件并稍后关闭它,我打印的是要保存在文件中的字符串,它显示字符串然后崩溃,我只是不知道为什么会发生这种情况。
stdin
cannot be flushed. stdin
不能被刷新。&(*txt) == txt
I think you struggle to understand what double pointers are for.我认为您很难理解双指针的用途。 You use them if you want to change the original pointer (single star one).如果要更改原始指针(单星指针),请使用它们。
An example - the pointer fi
will be modified in the function weirdopen
:一个例子——指针fi
将在weirdopen
中修改:
void weirdopen(FILE **f, const char *filename)
{
*f = fopen(filename, "r");
}
void myread(FILE *f, char *str, const size_t size)
{
fgets(str, size, f);
}
int main(void)
{
FILE *fi;
char str[100];
weirdopen(&fi, "test.txt");
myread(fi, str, 100);
fclose(fi);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.