简体   繁体   中英

file system api read/write confusion

I tried to read 7 bytes from the file self_tutor.txt into the buff. But somehow the read was not successful. I have checked the syntax for read and the corresponding parameters to be used, but I am not sure where the error comes from. Also what would be the proper way of outputting value from buff if buff was successfully write with the 7 bytes of values from self_tutor.txt?

will a while loop work?

// will this work if the total number of bytes is less than I request? like there
// is only 5 bytes in the self_tutor.txt file but I request to read 7? (i.e. short-read)

while(buff!= EOF) {  // will EOF work if I have short-read
   printf("value of character inside the buff:%c\n ", *buff);
   buff++;
}

or should it be:
while(buff!= "\n") {  // so "\n" will be able to handle short-read, is it correct?
   printf("value of character inside the buff:%c\n ", *buff);
   buff++;
}
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
    printf("Hello World\n");
    int f1 = open("self_tutor.txt", O_RDONLY);
    char *buff;
    int f2 = read(f1, buff, 7);
      printf("value of f2 :%d\n ", f2); // f2 = -1, so read was not successful
      
     // how to print all the bytes in buff from beginning of buff to end of buff
    printf("value of buff:%c\n ", *buff);
   
    return 0;
}


this is the contents of my self_tutor.txt file:

In our Y86-64 simulator. This course is pretty interesting but hard. 

A related question is: A short read may indicate end of file but does not necessarily do so.

what does it mean, does it mean if I have a short-read the following read(f1, buff, 7);

will not necessarily produce the value 0? ie read(f1, buff, 7) might equal a non-zero value?

thanks

You code never assigns any value to buff . So you are passing garbage to read . You need to make buff point to the place you want the character you read to be stored before you pass its value to read .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM