【问题标题】:Write contents of text file to an array of file blocks (512 Bytes) in C++将文本文件的内容写入 C++ 中的文件块数组(512 字节)
【发布时间】:2018-03-29 20:43:46
【问题描述】:

我正在尝试将 5 KB 文本文件分成 10 个块的文件数组,每个块为 512 字节。

我已正确加载文件并写入 char 数组,但我不明白下面的 while(infile >> temp[i]) 发生了什么。 这是否意味着“当 test1.txt 仍有字符要写入时,将其写入temp[]”?

基本上,我希望 input1.txt 中的字符 0 到 511 加载到 temp[] 中,然后将 temp 存储在 fileArray[0] 中。然后将字符 512 到 1023 加载到 temp[] 中,然后存储到 fileArray[1] 中,依此类推。如果文件小于 5 KB,则用 0 填充 fileArray[] 中的其余项目。

代码:

    FILE* fileArray[10];
//something like for(int a = 0; a < fileArray.length; a++)
    ifstream infile;
    int i = 0;
    int k = 0;
    char temp[512];
    infile.open("inputFiles/test1.txt");  //open file in read mode.. IF FILE TOO BIG, CRASHES BECAUSE OF TEMP
    while (infile >> temp[i])//WHAT DOES THIS MEAN?
        i++;

    k = i;
    for (int i = 0; i < k; i++) {
        cout << temp[i]; //prints each char in test1.txt
    }

新代码:

FILE* input = fopen(filename, "r");
if (input == NULL) {
    fprintf(stderr, "Failed to open %s for reading OR %s is a directory which is fine\n", filename, filename);
    return;
}

FILE **fileArray = (FILE**) malloc(10 * 512); //allow files up to 5.12KB (10 sectors of 512 Bytes each)
                     //load file into array in blocks of 512B
                     //if file is less than 5.12KB fill rest with 0's

    std::filebuf infile;
infile.open("inputFiles/test1.txt", std::ios::in | std::ios::binary);

for (int a = 0; a < 10; a++) {
    outfile.open(fileArray[a], std::ios::out | std::ios::binary);
    int block = 512 * a;
    int currentBlockPosition = 0;
    while (currentBlockPosition < 512) {
        std::copy(std::istreambuf_iterator<char>(&infile[block + currentBlockPosition]), {},
            std::ostreambuf_iterator<char>(&outfile));


        //input[block * currentBlockPosition] >> fileArray[a];
        //currentBlockPosition++;
    }
}

【问题讨论】:

  • 发布minimal reproducible exampleFILE* 很可能是个错误。
  • FILE* fileArray[10]; 你打算打开 10 个文件,每个文件 512 字节吗?
  • @KillzoneKid 是的
  • 您的 新代码 看起来像 C,而您将问题标记并命名为 C++。这非常令人困惑。
  • @KillzoneKid 谢谢,我再次更新,但我仍然担心FILE **fileArray = (FILE**) malloc(10 * 512);。这种类型的文件数组是 C 特有的,还是也可以在 C++ 中使用?

标签: c++ file io


【解决方案1】:

while (infile >> temp[i])//这是什么意思? 我++; // 这意味着当文件中存在数据时,将这些数据放入临时数组中

我认为从文件中获取整个数据然后拆分数组是个好主意

【讨论】:

  • 感谢您的帮助。我认为您是对的,我在答案中添加了 New Code 部分。
猜你喜欢
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2014-02-28
  • 2014-04-10
相关资源
最近更新 更多