fwrite 写入一个整数
我正在尝试使用此函数将一个单词写入文件:
extern void write_int(FILE * out, int num) {
fwrite(&num,sizeof(int),1, out);
if(ferror(out)){
perror(__func__);
exit(EXIT_FAILURE);
}
}
但是每当它尝试运行 fwrite 时,我都会遇到分段错误。我查看了 fwrite(3) 的手册页,我觉得我使用它是正确的,有什么我遗漏的吗?
I'm trying to write a word to a file using this function:
extern void write_int(FILE * out, int num) {
fwrite(&num,sizeof(int),1, out);
if(ferror(out)){
perror(__func__);
exit(EXIT_FAILURE);
}
}
But I get a segmentation fault whenever it tries to run the fwrite. I looked at the man page for fwrite(3) and I feel like I used it correctly, is there something I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
为什么你原来的函数是
extern
?Try this instead:
And why was your original function
extern
?文件句柄有效吗?你用“w”fopen()了吗?如果不是,fwrite() 将会出现段错误。
该函数本身实际上什么也没做,所以显然 fwrite 调用才是问题所在。检查论点。
Is the file handle valid? Did you fopen() with "w"? fwrite() will segfault if it's not.
The function itself really does nothing, so it's obviously the fwrite call that's the problem. Examine the arguments.
out
不包含文件的地址,而是包含您在 main 中传递的文件指针的地址。这个函数原型应该是这样的:通过这种方式,您可以创建一个指向 main 中的指针的双指针,然后该指针指向该文件。
out
does not contain the address of the file, rather it contains the address of the file pointer your passing in main. This function prototype should be like:In this way you are making a double pointer to the pointer in main which is then pointing to the file.