在C ++中将文本文件的内容写入文件块(512字节)数组

时间:2018-03-29 20:43:46

标签: c++ file io

我正在尝试将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++;
    }
}

1 个答案:

答案 0 :(得分:0)

while(infile&gt;&gt; temp [i])//这意味着什么?         我++; //这意味着文件中存在数据时将此数据放入临时数组

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

是个好主意