7

I get a segmentation fault with this code on fprintf:

#define _GNU_SOURCE

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdint.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>

int fd;
int main(int argc, char **argv) {
    fd = posix_openpt(O_RDWR | O_NOCTTY);

    fprintf(fd, "hello\n");

    close(fd);
}

But it works fine with:

fprintf(stderr, "hello\n");

What is causing this?

Nick Udell
  • 2,420
  • 5
  • 44
  • 83
muebau
  • 152
  • 7

3 Answers3

10

You have a segfault, because fd is an int, and fprintf except of a FILE*.

fd = posix_openpt(O_RDWR | O_NOCTTY);
fprintf(fd, "hello\n");    
close(fd);

Try fdopen over that fd:

FILE* file = fdopen(fd, "r+");
if (NULL != file) {
  fprintf(file, "hello\n");    
}
close(fd);
NoDataFound
  • 11,381
  • 33
  • 59
5

You are trying to pass the file descriptor (used for low-level file access) to fprintf, but it actually needs a FILE structure, defined in stdio.h.

You could use dprintf or fdopen (which are POSIX).

Jay
  • 9,585
  • 6
  • 49
  • 72
3

To write out to a file descriptor use write(). The fprintf command requires a FILE* typed pointer.

#define _XOPEN_SOURCE 600

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

int main(void)
{
  int result = EXIT_SUCCESS;
  int fd = posix_openpt(O_RDWR | O_NOCTTY);
  if (-1 == fd)
  {
    perror("posix_openpt() failed");
    result = EXIT_FAILURE;
  }
  else
  {
    char s[] = "hello\n";
    write(fd, s, strlen(s));

    close(fd);
  }

  return result;
}
alk
  • 69,737
  • 10
  • 105
  • 255