#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdint.h>
int main()
{
int file;
off_t offset;
if((file=open("testfile.txt",O_RDONLY)) < -1)
return 1;
char buffer[19];
if(read(file,buffer,19) != 19) return 1;
fprintf(stdout,"%s\n",buffer);
if(offset = lseek(file,-19,SEEK_END) < 0) return 1;
fprintf(stdout,"%jd\n",(intmax_t)offset);
if(read(file,buffer,19) != 19) return 1;
fprintf(stdout,"%s\n",buffer);
return 0;
}
The Output is as follows:
This is a test file��
0
his is a test file
��
testfile.txt :
This is a test file Testing how SEEK_END works This is a test file
I have tried different formatting for offset, such as %ld,%d, but the output is still the same. Can't figure out why garbage appears at the end of first line and last line. Please help.
Other answers have already offered solutions for the problem with printing
buffer
. This answer addresses the other question in your post.Due to operator precedence, the line
is equivalent to:
I am sure you meant to use:
You need to leave room for an end of line character, '\0';
So make
char buffer[19];
char buffer[20];
then also addbuffer[19] = '\0';
- remember it's zero based counting. Then it shouldn't have the garbage data.The reason is because printf doesn't know where the end is of the character array. So it keeps printing until it finds a '\0' in garbage memory.
read does not know anthing about strings, it reads bytes from a file. so if you read in 19 bytes into "buffer" and there is no terminating \0 then it is not a valid string.
So either you need to ensure that your buffer is 0 terminated or print out only the first 19 bytes e.g.
printf( "%.*s", sizeof(buffer), buffer );
or extend the buffer for the \0 e.g.char buffer[20] = {0};
You should also open the file like this in order to make sure lseek works (file must be opened in binary mode)
it is always good to give an error message when something fails instead of just terminating the program.