繁体   English   中英

文件系统 api 读/写混乱

[英]file system api read/write confusion

我试图从文件 self_tutor.txt 中读取 7 个字节到 buff 中。 但不知何故,阅读没有成功。 我已经检查了 read 的语法和要使用的相应参数,但我不确定错误来自哪里。 另外,如果使用 self_tutor.txt 中的 7 字节值成功写入 buff,从 buff 输出值的正确方法是什么?

while循环会起作用吗?

// 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;
}


这是我的 self_tutor.txt 文件的内容:

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

一个相关的问题是:短读可能表示文件结束,但不一定如此。

这是什么意思,如果我有一个简短的阅读以下阅读(f1,buff,7),这意味着什么?

不一定会产生值0? 即 read(f1, buff, 7) 可能等于非零值?

谢谢

您的代码永远不会为buff分配任何值。 所以你正在传递垃圾read 在将其值传递给read之前,您需要将buff指向您希望存储所读取字符的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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