Printf printing garbage after read() call. The offset is always printed as 0

后端 未结 3 1470
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 07:34
#include 
#include 
#include 
#include 
#include 

int main()
{
    int file;
    of         


        
相关标签:
3条回答
  • 2020-12-12 07:56

    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;
    
    0 讨论(0)
  • 2020-12-12 08:03

    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.

    0 讨论(0)
  • 2020-12-12 08:11

    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.

    0 讨论(0)
提交回复
热议问题