C语言 fwrite 写一个整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2695934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:16:09  来源:igfitidea点击:

fwrite write an integer

csegmentation-faultfwrite

提问by user149100

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?

但是每当它尝试运行 fwrite 时,我都会遇到分段错误。我查看了 fwrite(3) 的手册页,我觉得我正确使用了它,是不是我遗漏了什么?

回答by tylerl

Try this instead:

试试这个:

void write_int(FILE * out, int num) {
   if (NULL==out) {
       fprintf(stderr, "I bet you saw THAT coming.\n");
       exit(EXIT_FAILURE);
   }
   fwrite(&num,sizeof(int),1, out);
   if(ferror(out)){
      perror(__func__);
      exit(EXIT_FAILURE);
   }
}

And why was your original function extern?

为什么是你原来的功能extern

回答by Paul Richter

Is the file handle valid? Did you fopen() with "w"? fwrite() will segfault if it's not.

文件句柄有效吗?你用“w” fopen() 吗?如果不是, fwrite() 将出现段错误。

The function itself really does nothing, so it's obviously the fwrite call that's the problem. Examine the arguments.

函数本身真的什么都不做,所以很明显 fwrite 调用就是问题所在。检查论据。

回答by Najeeb Uddin

outdoes 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:

out不包含文件的地址,而是包含您在 main.js 中传递的文件指针的地址。这个函数原型应该是这样的:

extern void write_int(FILE * & out, int num);

In this way you are making a double pointer to the pointer in main which is then pointing to the file.

通过这种方式,您将创建一个指向 main 中的指针的双指针,然后该指针指向该文件。