Printf printing garbage after read() call. The off

2020-02-07 12:34发布

#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.

3条回答
我想做一个坏孩纸
2楼-- · 2020-02-07 13:03

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

if(offset = lseek(file,-19,SEEK_END) < 0) return 1;

is equivalent to:

if(offset = (lseek(file,-19,SEEK_END) < 0)) return 1;

I am sure you meant to use:

if( (offset = lseek(file,-19,SEEK_END)) < 0) return 1;
查看更多
不美不萌又怎样
3楼-- · 2020-02-07 13:14

You need to leave room for an end of line character, '\0';

So make char buffer[19]; char buffer[20]; then also add buffer[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.

查看更多
闹够了就滚
4楼-- · 2020-02-07 13:19

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)

if((file=open("testfile.txt",O_RDONLY|O_BINARY)) == -1) // returns -1 by failure
{
  perror("testfile.txt"); // to get an error message why it failed.
  return 1;
}

it is always good to give an error message when something fails instead of just terminating the program.

查看更多
登录 后发表回答