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

ved*_*ala 2 c++ file unistd.h fcntl

以下是在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;

} 
Run Code Online (Sandbox Code Playgroud)

编译时; 我收到这条消息:

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";
Run Code Online (Sandbox Code Playgroud)

执行时:

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.
Run Code Online (Sandbox Code Playgroud)

可以在此处找到整个gdb调试.

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

Ts.mp4 权限

And*_*nle 5

假设您正在运行Linux,则errno值为14 EFAULT,或"错误地址".

鉴于代码

char* pBuffer;
  .
  .
  .
int ret = read(filedes,pBuffer,NumBytesToRead);
Run Code Online (Sandbox Code Playgroud)

pBuffer未初始化或以其他方式设置,因此值pBuffer不确定,并且它当然不指向有效地址.

您需要实际提供一个read()可以放置数据的缓冲区:

char buffer[ 1024 ]
   .
   .
   .
ssize_t ret = read(filedes,buffer,NumBytesToRead);
Run Code Online (Sandbox Code Playgroud)

只要NumBytesToRead不超过中的字节数buffer就可以工作. 还要注意,ret现在是正确ssize_t而不是int.