Reputation: 164
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?
Upvotes: 7
Views: 345
Reputation: 70911
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;
}
Upvotes: 3
Reputation: 9656
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).
Upvotes: 5
Reputation: 11949
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);
Upvotes: 10