What I only want written to the file descriptor is the input string. However, it also writes the error messages passed in fprintf. Can someone explain why it is behaving like this? This small program shows the behavior.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int fd;
mode_t mode = S_IRUSR | S_IWUSR;
char *filename = "file.txt";
char *input = "hello world";
char output[20];
// create and close
if((fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, mode)) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
close(fd);
// just open
if((fd = open(filename, O_RDWR, mode)) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
if(write(fd, input, 200) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
// move back to beginning
if(lseek(fd, 0, SEEK_SET) == -1)
{
return -1;
}
if(read(fd, &output, 200) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
printf("%s\n", output);
return 0;
}
You’re writing and reading well past the arrays that contain valid data – neither
inputnoroutputare anywhere close to 200 bytes. So who knows what’s going to end up in the file (and I’m not sure why theread()doesn’t crash your program)?