1

我正在尝试一个基本程序setvbuf

int main(int argc, char **argv) {

    FILE * fp;
    char buffer[1024];

    fp = fopen("~/my.txt", "w");

    setvbuf(fp, buffer, _IOFBF, sizeof(buffer));

    return EXIT_SUCCESS;
}

当我运行程序时,我遇到了分段错误setvbuf

Breakpoint 1, main (argc=0, argv=0x20) at ../my.c:13
13      int main(int argc, char **argv) {
(gdb) n
18              fp = fopen("~/my.txt", "w");
(gdb) n
20              setvbuf(fp, buffer, _IOFBF, sizeof(buffer));
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()

我的环境是:

$ uname -a
CYGWIN_NT-6.1 myhost 1.7.25(0.270/5/3) 2013-08-31 20:37 x86_64 Cygwin
$ gcc --version
gcc (GCC) 4.8.1
4

1 回答 1

1

根据Oli 的评论Paul R 的评论,我添加了适当的错误处理:

fp = fopen("~/my.txt", "w");
if (fp == NULL)
  {
    perror ("The following error occurred");
    printf( "Value of errno: %d\n", errno );
    return EXIT_FAILURE;
  }

输出是:

The following error occurred: No such file or directory
Value of errno: 2

将文件路径修复为完整路径后,调用setvbuf成功。

于 2013-09-23T08:36:11.307 回答