c++ - 无法使用 read() 将文件内容读入缓冲区

标签 c++ file fcntl unistd.h

以下是在 Ubuntu OS 16.04 上使用 GNU 编译器(g++ 命令)编译的示例代码:

#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include <errno.h>
int main()
{           char* pBuffer;          

            char* storedfilepath = "/home/rtpl/Desktop/ts.mp4";

            std::cout<<"\n Opening file at "<<storedfilepath<<"\n";

            int NumBytesToRead = 1000 ;
            int filedes = open(storedfilepath,O_RDONLY);

            std::cout<<"\n value of error is "<<errno<<"\n";

            std::cout<<"\n value of filedes is "<<filedes;

            if (filedes==0)
            std::cout<<"\n File cannot be opened";
            else
            {
            std::cout<<"\n File opened successfully";
            std::cout<<"\n Now reading file\n"; 

            }

            //if(
            int ret = read(filedes,pBuffer,NumBytesToRead);

            std::cout<<"\n value of error is "<<errno<<"\n";

            if(ret!= -1)
            std::cout<<"\n File read successfully";
            else
            std::cout<<"\n File contents cannot be read";   

            std::cout<<"\nEnd.\n";  

            close(filedes);
            return 0;

} 

编译时;我收到此消息:

rtpl@rtpl-desktop:~/Desktop$ g++ -g checkts.cpp
checkts.cpp: In function ‘int main()’:
checkts.cpp:8:27: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
    char* storedfilepath = "/home/rtpl/Desktop/ts.mp4";

执行后:

rtpl@rtpl-desktop:~/Desktop$ ./a.out

 Opening file at /home/rtpl/Desktop/ts.mp4

 value of error is 0

 value of filedes is 3
 File opened successfully
 Now reading file

 value of error is 14

 File contents cannot be read
End.

可以找到整个 gdb 调试 here .

问题:当文件合法并且编译器没有抛出错误时,为什么无法读取文件内容?

Ts.mp4 permissions

最佳答案

假设您运行的是 Linux,errno 值 14 是 EFAULT,即“错误地址”。

给定代码

char* pBuffer;
  .
  .
  .
int ret = read(filedes,pBuffer,NumBytesToRead);

pBuffer 未初始化或以其他方式设置,因此 pBuffer 中的值是不确定的,它肯定不会指向有效的地址。

您实际上需要提供一个缓冲区,其中 read() 可以放置读取的数据:

char buffer[ 1024 ]
   .
   .
   .
ssize_t ret = read(filedes,buffer,NumBytesToRead);

只要NumBytesToRead不超过缓冲区中的字节数就可以工作。另请注意ret 现在是正确的 ssize_t,而不是 int

关于c++ - 无法使用 read() 将文件内容读入缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47175465/

相关文章:

c - O_NONBLOCK 是否被设置为文件描述符或基础文件的属性?

python - Docker 和 fcntl OSError Errno 22 参数无效

c++ - 模板和类型定义

java-如何指定我与源代码一起存储的文件的路径

ruby-on-rails - Ruby:遍历目录和文件

C程序不计算文本文件中的字母频率

c++ - 如何判断当前进程是否已经锁定了一个文件?

c++ - C++20 keys_view 和 values_view 的真正目的是什么?

c++ - 抛出临时变量而不是局部变量 - 为什么?

c++ - 组织项目的文件以实现多平台和易于使用