[英]Read/write binary file in C++
How can I create a linux I/O benchmark for read and write operations of binary file using C++? 如何使用C ++为二进制文件的读写操作创建linux I / O基准测试?
I have tried to generate a file of 10MB with the code below but it returns me "segmentation fault (core dumped)". 我尝试使用下面的代码生成10MB的文件,但它返回“段错误(核心已转储)”。
#define FILE_SIZE 10240
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
int fd, i;
int stream[FILE_SIZE];
double span;
clock_t start,end;
start=clock();
fd=open("data.bin", O_CREAT|O_TRUNC|O_WRONLY, S_IRWXU);
srand(time(NULL));
for(i=0; i<FILE_SIZE; i++){
stream[i]=rand()%2;
write(fd, (char*)stream[i], strlen((char*)stream[i]));
}
for(i=0; i<FILE_SIZE; i++)
read(fd, (char*)stream[i], strlen((char*)stream[i]));
close(fd);
end=clock();
time_lapse=((double)(end-start))/CLOCKS_PER_SEC;
return 0;
}
Then it returns me some warnings due to the conversion included in the write and read functions, I'm sure there is a better way to do this. 然后,由于写入和读取功能中包含的转换,它会向我返回一些警告,我敢肯定有更好的方法可以做到这一点。
Could anyone help me? 有人可以帮我吗?
Thanks in advance, Antonio 预先感谢,安东尼奥
Your biggest problem is that you treat stream[i]
as a string! 您最大的问题是将
stream[i]
视为字符串! It's not a string, it's an int
value. 它不是字符串,而是
int
值。
Use &stream[i]
to get a pointer to it, and use sizeof stream[i]
to get its size. 使用
&stream[i]
获取指向它的指针,并使用sizeof stream[i]
获取其大小。 In fact, you don't need to write each element separately, you could just write the whole array at once: 实际上,您不需要单独编写每个元素,您可以一次编写整个数组:
write(fd, stream, sizeof stream);
You could read it just the same. 您可以阅读相同的内容。
A big sign of the problem is that you need to use C-style casting. 问题的一个明显迹象是,您需要使用C样式转换。 If you need to do it in C++ then it's a sing of you doing something you should not.
如果您需要用C ++来做,那是您不应该做的一件事。
Besides that you're not really doing anything C++-specific, your code could be plain C. 除此之外,您实际上并没有做任何特定于C ++的事情,您的代码可以是纯C语言。
A C++ solution would be using std::fstream
instead. C ++解决方案将改为使用
std::fstream
。
If you still need to use the POSIX low-level function, don't forget error checking . 如果您仍然需要使用POSIX低级功能,请不要忘记进行错误检查 。 Each of the function you call could fail.
您调用的每个函数都可能失败。 And that actually includes the call to
close
. 这实际上包括
close
的调用。
strlen((char*)stream[i])
is wrong because stream[i]
is int
, not char*
. strlen((char*)stream[i])
是错误的,因为stream[i]
是int
,而不是char*
。 Hence, strlen
will keep on reading memory until it finds a 0 byte or runs off the mapped memory and you get a SIGSEGV
. 因此,
strlen
会继续读取内存,直到找到0字节或耗尽映射的内存为止,您会得到SIGSEGV
。
Fix: sizeof stream[i]
. 修复:
sizeof stream[i]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.