#include <stdio.h>
#include <stdlib.h>
int main ( int argc, char *argv[] )
{
//sets the number of lines ot be read
char strline[10000];
// checks to see that there are only 2 entries in the argv by checking in argc
if ( argc != 2 )
{
printf( "ERROR. Enter a file name\n", argv[0] );
}
else
{
//opens the file which was entered by the user as read only
FILE *infile = fopen( argv[1], "r");
// covers a miss spelling of a file name or file doesn't exist
if ( infile == 0 )
{
printf( "ERROR. Did you make a mistake in the spelling of the file or the File entered doesn't exist\n" );
}
else
{
// File exists read lines, while not at the end of the file
while (!feof(infile))
{
//Get next line to be printed up to 126 characters per a line
if(fgets(strline, 126, infile))
{
//print the current line (stored in strline)
printf("%s",strline);
}
}
//closes the file
fclose( infile );
return 0;
}
}
}
在第6行(上面的评论)我已经声明这是程序可以读取的最大行数。昨天我被告知事实并非如此。
有人可以向我解释代码行的实际含义吗?
char strline[10000];
所以从人们所说的是什么设置为128更多的东西(126为fgets和一些房间)
答案 0 :(得分:3)
char strline [10000];您已经分配了一个10,000字节长的缓冲区:
+--------------...-+
strline -> | 10000 |
+--------------...-+
如果你想分配10,000行而你需要这样的东西:
char* strline[10000]; // array of 10,000 pointers to strings
访问行将分配给数组中的每个条目
strline[0]
strline[1]
...
strline[10000]
比如读取一行时你需要为该行分配一个缓冲区,然后从strline指向它
char* line = malloc( linelength + 1 );
fgets( line, linelength, fp );
strline[0] = line;
+-------+
strline[0] -> | line |
+-------+