Reputation: 3
I am trying to make a simple client and server. Right now I am able to prints the contents of a file out to the screen. I would now like to store every line i read from the buffer into an array. I have attempted this but for some reason it always just adds the last line received from the buffer. Can anyone point out where I have gone wrong
int getFile (char path[256], int fd)
{
char buffer[256];
char bufferCopy[256];
char arguments[1000][1000];
int total = 0;
char * ptr;
while(read(fd, buffer, 256) != NULL)
{
char * temp;
strcpy(arguments[total], buffer);
total++;
}
for(int i = 0; i < total; i++)
{
printf("\n %s", arguments[i]);
}
}
Upvotes: 0
Views: 665
Reputation: 434745
Your read
call doesn't read lines, it reads up to 256 bytes from fd
. read
also doesn't know anything about null terminators so there is no guarantee that buffer
will hold a string (i.e. have a null terminator) and hence no guarantee that strcpy
will stop copying at a sensible place. You're almost certainly scribbling all over your stack and once you do that, all bets are off and you can't expect anything sensible to happen.
If you want to read lines then you might want to switch to fgets
or keep using read
and figure out where the EOLs are yourself.
Upvotes: 2