我正在读取文件,以将文本保存到数组中。文本最终要保存到的数组是plainText []。不过,奇怪的是,fgets()不能读取整个文件。在停止之前,它只读取文件的一半。
这是文件的完整内容:
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
bbbbbbbbb
有8行b,每列9行,总计72 b。我得到的输出在打印时仅包含36 b。
打印plainText []时的输出:
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
这是打开和读取文件的代码。
int main(int argc, char **argv) {
//send an error code if the correct number of arguments have not been met to run the program
if (argc < 3) {
printf("Please enter the encryption file and the file to be encrypted.\n");
return ERROR;
}
//open file to be encrypted (aka, plaintext)
char *fileToEncrypt = argv[2];
FILE *plainFile = fopen(fileToEncrypt, "r");
//return an error code if the file to encrypt cannot be found
if (plainFile == 0) {
printf("The file you wish to encrypt cannot be found on this machine.\n");
printf("Please ensure that you are in the correct directory and that there are no typos.\n");
return ERROR;
}
这是我使用fgets()读取文件内容并将其传输到plainText []的地方。
//read contents of file to encrypt
char plainText[STRING_LENGTH + 1], temp2[STRING_LENGTH + 1];
//fill array with null terminators so we don't receive
//memory errors from strcat(plainText, temp2)
for (int i = 0; i < STRING_LENGTH; i++)
plainText[i] = '\0';
//pointer to end of string in order to remove \n
char *bptr = plainText;
//read the file again if it is found there are multiple lines
while (fgets(temp2, STRING_LENGTH, plainFile)) {
fgets(temp2, STRING_LENGTH, plainFile);
strcat(plainText, temp2);
bptr[strlen(bptr) - 1] = '\0'; //remove \n at end of string at a result of fgets()
}
//close file
fclose(plainFile);
循环告诉fgets()只要有内容就继续读取,但是fgets()停止在文件中途输入内容。为什么呢?
答案 0 :(得分:2)
fgets
每次在条件中被调用时将一行读入缓冲区
while (fgets(temp2, STRING_LENGTH, plainFile)) {
然后您再次直接调用它,使其读入第二行:
fgets(temp2, STRING_LENGTH, plainFile);
如果删除第二行,您的代码应该可以正常工作。
您的代码当前无法正常运行,因为它仅使用strcat
每隔一行复制一次。
答案 1 :(得分:2)
在循环中:
while (fgets(temp2, STRING_LENGTH, plainFile)) {
fgets(temp2, STRING_LENGTH, plainFile);
strcat(plainText, temp2);
bptr[strlen(bptr) - 1] = '\0'; //remove \n at end of string at a result of fgets()
}
每次调用fgets()
时,每隔两行都会被丢弃。您看不到这是因为您的所有行都是相等的,如果在文件中用不同的行对其进行测试,这将变得显而易见。
要解决此问题,您可以尝试:
while (fgets(temp2, STRING_LENGTH, plainFile)) {
strcat(plainText, temp2);
bptr[strlen(bptr) - 1] = '\0'; //remove \n at end of string at a result of fgets()
}