Reputation: 179
Im having an issue using the read() function in C.
I have a file lets say fileX which has the contents:
Data to be outputted
However when I open the file and use read on it I get garbage data using the code below
ssize_t reader = 0;
ssize_t writer = 0;
char buffer[256];
reader = read(myFile, buffer, 256);
//check if reader is -1, if so then exit(1)
writer = write(1, buffer, 256);
//check if writer is -1, if so then exit(1)
The read function seems to run twice. Once with a bunch of garbage data then followed by the actual data in the file. Any idea how to remedy this?
Upvotes: 0
Views: 142
Reputation: 625
Are you sure that your buffer is filled with '\0', finished with '\0' ? And you call write with 256 - in 3rd arg
#include <fcntl.h>
int main() {
const int max_size = 256;
char buffer[max_size] = {};
int my_input = open("input", O_TEXT, S_IREAD);
ssize_t reader;
ssize_t writer;
reader = read(my_input, buffer, max_size);
if(reader != -1)
writer = write(1, buffer, reader);
return 0;
}
Upvotes: 1