Reputation: 29
When I try read data from file and print it, printf prints an empty string to terminal.
Use: Ubuntu 16.04.
gcc version 5.4.0.
kernel: 4.15.0-43-generic
Tried:
add fsync call after writing data.
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#define SIZE 6
int main()
{
int ret = -1;
char buffer[SIZE] = { 0 };
int fd = open("data.txt", O_CREAT | O_RDWR, 0666);
if (fd < 0)
{
perror("open()");
goto Exit;
}
if (write(fd, "Hello", 5) < 0)
{
perror("write()");
goto Exit;
}
fsync(fd);
if (read(fd, buffer, SIZE - 1) < 0)
{
perror("read()");
goto Exit;
}
printf("%s\n", buffer);
ret = 0;
Exit:
close(fd);
return ret;
}
Expected: should write and read data from/to file.
Actual: data writes to file. After reading data, printf prints an empty string.
Upvotes: 1
Views: 240
Reputation: 136425
After writing you need to rewind the file.
Fix:
lseek(fd, 0, SEEK_SET);
Note that generally you do not need to zero-initialize your read buffers, that is a waste of time. You should rather use the return value of read
/recv
to determine the length of the received data and zero-terminate it manually, if necessary.
Fix:
ssize_t r = read(fd, buffer, SIZE - 1);
if (r < 0)
// handle error
buffer[r] = 0; // zero-terminate manually.
printf("%s\n", buffer);
Upvotes: 2