简体   繁体   中英

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++?

I have tried to generate a file of 10MB with the code below but it returns me "segmentation fault (core dumped)".

#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! It's not a string, it's an int value.

Use &stream[i] to get a pointer to it, and use sizeof stream[i] to get its size. 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. If you need to do it in C++ then it's a sing of you doing something you should not.


Besides that you're not really doing anything C++-specific, your code could be plain C.

A C++ solution would be using std::fstream instead.

If you still need to use the POSIX low-level function, don't forget error checking . Each of the function you call could fail. And that actually includes the call to close .

strlen((char*)stream[i]) is wrong because stream[i] is int , not 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 .

Fix: sizeof stream[i] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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