C++ Get all bytes of a file in to a char array?

后端 未结 3 1769
礼貌的吻别
礼貌的吻别 2020-12-03 12:32

Given:

const string inputFile = \"C:\\MyFile.csv\";
char buffer[10000];

How do I read the chars of the file in to the above buffer? I have

3条回答
  •  盖世英雄少女心
    2020-12-03 13:02

    If you're concerned with efficiency (you rejected getline()) then a C-style mmap is probably best:

    #include 
    #include 
    
    struct stat s;
    stat(inputFile.c_str(), &s);
    size_t file_size = st.st_size;
    
    int fhand = open(inputFile);
    char* file_buf = (char*)mmap(0, file_size, PROT_READ, MAP_FILE|MAP_PRIVATE, fhand, 0);
    ...
    munmap(file_buf, file_size);
    

提交回复
热议问题