我有以下代碼:文件需要讀取正確
int main(void)
{
int lines_allocated = 128;
int max_line_len = 100;
int lines_allocated2 = 128;
int max_line_len2 = 100;
/* Allocate lines of text */
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
if (words == NULL)
{
fprintf(stderr, "Out of memory (1).\n");
exit(1);
}
FILE *fp = fopen("test1.txt", "r");
if (fp == NULL)
{
fprintf(stderr, "Error opening file.\n");
exit(2);
}
else
{
printf("Reading in test1.txt...\n");
}
int i;
for (i = 0; 1; i++)
{
int j;
/* Have we gone over our line allocation? */
if (i >= lines_allocated)
{
int new_size;
/* Double our allocation and re-allocate */
new_size = lines_allocated * 2;
words = (char **)realloc(words, sizeof(char*)*new_size);
if (words == NULL)
{
fprintf(stderr, "Out of memory.\n");
exit(3);
}
lines_allocated = new_size;
}
/* Allocate space for the next line */
words[i] = malloc(max_line_len);
if (words[i] == NULL)
{
fprintf(stderr, "Out of memory (3).\n");
exit(4);
}
if (fgets(words[i], max_line_len - 1, fp) == NULL)
break;
/* Get rid of CR or LF at end of line */
for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--)
;
words[i][j] = '\0';
}
int j;
for (j = 0; j < i; j++)
{
printf("%s\n", words[j]);
}
return 0;
}
我想在一個文件中讀取和存儲的話陣列中的每一行。我的輸入文件包含:
1 345363
0 149378
0 234461
0 454578
但是,每行的最後一個數字被截斷。因此,第一個索引將打印34536,當它打印出345363.我似乎無法弄清楚什麼是錯的。
僅供參考:[不要強制轉換'malloc'的返回值](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 –
你最後一個字符被設置爲'\ 0' – mgamba