简体   繁体   English

将字符写入文件C ++

[英]Write chars into file C++

I have a function that writes random numbers into a file while reading another file. 我有一个在读取另一个文件时将随机数写入文件的功能。

void writeFile() {
    FILE* file = fopen(source, "r");
    FILE* file2 = fopen(target, "w");
    srand (time(NULL));

    while (!feof(file)) {
        fgetc(file);
        fputc(0 + ( rand() % ( 50 - 0 + 1 ) ), file2);
    }


    fclose(file);
    fclose(file2);
}

The two files should have the same size. 这两个文件应具有相同的大小。 What happens is that the second file has more 1byte at the end compared with the first file. 发生的情况是第二个文件的末尾比第一个文件多1byte。 How can I avoid this? 如何避免这种情况?

As well as the EOF comments, you should also open both files in binary mode 除了EOF注释之外,您还应该以二进制模式打开两个文件

FILE* file = fopen(source, "rb");
FILE* file2 = fopen(target, "wb");

In non-binary mode line endings may be translated (depending on platform). 在非二进制模式下,行尾可以翻译(取决于平台)。 This potentially changes the number of characters read or written to a file. 这可能会更改读取或写入文件的字符数。

Don't rely on feof to tell you that you've read all characters. 不要依靠feof的东西告诉你已经阅读了所有字符。 Instead, check the return value from fgetc : 相反,请检查fgetc的返回值:

while (fgetc(file) != EOF) {
    fputc(0 + ( rand() % ( 50 - 0 + 1 ) ), file2);
}

The very final fgetc(file) reads EOF, then your code writes a byte for it into the new file and only then it tests for feof in the while . 最后的fgetc(file)读取EOF,然后您的代码将其写入新文件中的一个字节, 然后才在while测试feof

Don't use feof , use this instead: 不要使用feof ,而是使用以下代码:

if (fgetc(file) == EOF) break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM