java怎么转C++呢

private String getFileContent(File file) {
String content = "";
if (!file.isDirectory()) {
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader
= new InputStreamReader(instream, "UTF-8");
BufferedReader buffreader = new BufferedReader(inputreader);
String line = "";
while ((line = buffreader.readLine()) != null) {
content += line;
}
instream.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}

这是一次读取完一个文件吧,有很多种方法。这里举2个典型的:

  1. 用fread按指定缓冲区大小循环读取完毕整个文件;
  2. 用文件流ifstream 按行读取完文件;
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
using namespace std;

/**
 * fread读取文件
 * 适合读小文件,一次读取完毕
 * @param filepath 文件路径
 * @return 文件文本内容
 */
string readFile(const char* filepath)
{
    assert(filepath != nullptr);
    FILE* fp;
    string content;
    char buf[1024]; // 自定义缓冲区大小

    // 获取文件大小
    struct stat st;
    if (stat(filepath, &st) < 0) {
        perror("stat error");
        return content;
    }
    int filelen = st.st_size;

    // 文本模式打开文件
    fp = fopen(filepath, "r");
    if (!fp) {
        perror("open file error");
        return content;
    }
    cout << "open file success: " << filepath << endl;
    int nleft = filelen;
    while (nleft > 0) {
        int nread = fread(buf, sizeof(buf[0]), sizeof(buf), fp); // 按1byte从fp读取最多buf缓冲区大小字节数
        if (nread == 0) { // complete reading
            break;
        }
        else {
            buf[nread] = '\0';
            content += buf;
            nleft -= nread;
        }
    }
    fclose(fp);
    return content;
}

#include <fstream>
/**
 * 文件流读取指定文件
 */
string readFileByStream(const char* filepath)
{
    string content;
    char buf[256];

    ifstream in("test.txt"); // 只读模式打开文件
    if (!in.is_open()) {
        cerr << "open file error: " << filepath << endl;
        return content;
    }

    while (!in.eof()) {
        in.getline(buf, sizeof(buf));
        content += buf;

        if (!in.eof()) { // ifstream::getline 会替换\n为\0, 还原时可根据需要加上\n
            content += '\n';
        }
    }
    return content;
}
// 测试用例,文件"test.txt"跟当前程序位于同一路径
int main()
{
    cout << readFileByStream("test.txt") << endl;
    cout << readFile("test.txt") << endl;
    return 0;
}