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

吠陀晚会

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

问题:当文件合法且编译器未引发任何错误时,为什么不读取文件内容?

Ts.mp4 权限

安德鲁·汉勒

假设您正在运行Linux,则errno值为14是EFAULT或“错误地址”。

给定代码

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

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

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

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

会工作,只要NumBytesToRead不超过字节数buffer另请注意,ret现在是,ssize_t而不是int

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将文件读入缓冲区

C编程:如何将整个文件内容读入缓冲区

如何将大文件读入缓冲区

Python 将文件读入缓冲区并在缓冲区已满时处理结果块

使用rdbuf将文件内容复制到缓冲区失败

为什么Rust的read_to_end不能将文件读入缓冲区?

文件流将十六进制文件读入二进制缓冲区

将二进制文件读入无符号字符向量缓冲区

从特定时间开始将AVAudioFile读入缓冲区

在将数据读入缓冲区的同时读取额外的字符

C++将整个进程内存读入缓冲区

将 zlib 流读入动态分配的缓冲区

我如何使用ubuntu中的终端将缓冲区中的某些内容直接粘贴到文件中?

将文件写入缓冲区

如何从缓冲区提取文件内容?

如何将内容输出到HttpServletResponse缓冲区?

无法将文件内容读入 std::string

从二进制文件读入char *缓冲区时访问violaton

大容量缓冲区fifo或使用文件作为fifo缓冲区

如何将Java Console输出读入字符串缓冲区

SPI 从设备将数据读入 stm32 上的缓冲区?

如何减少配置以将未显示的数据读入缓冲区?

无法使用 nodejs 将 url 图像响应转换为缓冲区

如何在不使用缓冲区的情况下将文件拆分到位?

如何在Linux中使用POSIX pthreads将整数从文件写入缓冲区?

如何在不使用缓冲区的情况下将文件拆分到位?

如何使用Python和gtk将文本缓冲区保存到文件?

使用缓冲区或流将Webshot存入Google云端硬盘而不存储中间文件?

使用python将文本从多个文件存储到字符串缓冲区