gpt4 book ai didi

C 读取文件行最大计数

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:40 24 4
gpt4 key购买 nike

#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 和一些空间)

最佳答案

字符字符串[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 |
+-------+

关于C 读取文件行最大计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8268397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com