C++ 读取一个文件

// 获取文件大小
long getFileSize(const char * const & filePath) {

    FILE *fp = fopen(filePath, "rb");

    if (fp == nullptr) {
        return -1;
    }

    fseek(fp, 0, SEEK_END);

    long fileSize = ftell(fp);

    fclose(fp);

    return fileSize;
}

int main() {

    const char *filePath = "log.txt";
    int size = getFileSize(filePath);

    // 不要在栈上申请空间,否则可能会导致栈溢出!
    char *buf = new char[size];
    memset(buf, 0, size);

    fstream  file;
    file.open(filePath, ios::binary|ios::in);
    if(!file.is_open()){
        std::cout<<"open fail"<

你可能感兴趣的:(C++ 读取一个文件)