C读取二进制数文件时会丢弃第一个字符



有人能帮助我理解为什么当我将文件大小增加到>时,从文件中读取的第一个字符会被丢弃吗;19排?

当我用<20行,它非常完美,读取输入并转储。当我添加第20行时,当我打印数组时,第一行输入会去掉前导字符。

我迷路了

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int i, j = 0;
FILE *pFile;
char string[20][12];
char file_contents_resultset[20][12];

pFile = fopen("sonar.txt", "r");
if (pFile == NULL)
{
printf ("error opening file");
return 0;
}
// Load 20 row of input into in an array and store a copy
for (i = 0; i < 20; i++)
{
fscanf (pFile, "%12s", &string[i]);
strcpy (file_contents_resultset[i], string[i]);
}
//Dump the first 5 rows of the array
printf ("Dump array contents n");
for (i = 0; i < 5; i++)
{
for (j = 0; j < 12; j++)
{
printf ("%c", file_contents_resultset[i][j]);
}
printf ("n");
}
fclose (pFile);
return 0;
};

这是我的输入文件。

000110010001
101000110000
000110010111
100011100010
111001100001
001010001010
010100100101
011000010000
111111011010
001111011101
011011010010
001100010101
001010101100
000000000000
100010111111
100100110011
111100100001
011110001110
000110100101
011101111001

这是输出

Dump array contents 
00110010001
101000110000
000110010111
100011100010
111001100001

如果我删除了输入文件中的第20行输入,这就是输出。请注意,第一个字符不再被丢弃。

Dump array contents 
000110010001
101000110000
000110010111
100011100010
111001100001

用于读取的一个数组是多余的。只能使用string[][]file_contents_resultset[][]

我发现你的问题出在strcpy()通话中。从缓冲区读取是可以的,但strcpy()似乎在file_contents_resultset[0][0]的内存位置复制了一个空白字符。

因此,通过保持程序的完整性来修复它,我做了:

// ...
// stores only one row at a time
char string[12];
// ...
for (int i = 0; i < 20; i++) {
fscanf(pFile, "%12s", &string);
strcpy(file_contents_resultset[i], string);
}
// ...
}

如果你想更简洁并节省内存,你可以完全删除string,只需写:

// ...
// char string[12];
char file_contents_resultset[20][12];
// ...
// brackets in loops and other blocks can be omitted
// if the block is just 1 line long. 
for (int i = 0; i < 20; i++)
fscanf(pFile, "%12s", &file_contents_resultset[20][12]);
// ...

最新更新