[英]How do I put each line in an array which read from the file in c program?
int main(int argc, char *argv)
{
char filename[20]={};
int count=0;
if(argc==2)
{
strcpy(filename, argv[1]);
}
else
{
printf("Need 2 command line parameters\n");
}
FILE *fp=fopen(argv[1], "r");
while(fgets(filename, 20, fp))
{
count++;
}
fseek(fp, 0, SEEK_SET);
int ptr=(int)malloc(count*sizeof(int));
while(fgets(filename, 20, fp))
{
ptr[i]=
}
return 0;
for example, my numbers in file are 19293 18239 19405 29302 10492 in each line, and I would like to put each line in an array.例如,我在文件中的数字是 19293 18239 19405 29302 10492 在每一行,我想把每一行放在一个数组中。 How do I do this?我该怎么做呢? It doesn't have to be in a while loop.它不必在一个while循环中。
I think your question is that you want to store the content you read as a string each line.Ok, there are serveal methods to realize it.我认为您的问题是您希望将读取的内容存储为每行的字符串。好的,有多种方法可以实现它。 If you don't care the effenciency, you can define a char pointer array as max as possible to contain all lines in your files.如果您不关心效率,您可以定义一个 char 指针数组,使其尽可能最大,以包含文件中的所有行。 And you can do like this:你可以这样做:
char* content[MAX_LINE] = { NULL };
char tmp[20];
char* ptr;
int i=0;
size_t ret;
FILE* fp;
fopen_s(&fp,"1.txt", "r");
while (fgets(tmp, 20, fp) != NULL)
{
ret = strlen(tmp);
ptr = (char*)malloc(ret+1);
strcpy_s(ptr, ret+1, tmp);
content[i++] = ptr;
}
And the better way is using pointer list.更好的方法是使用指针列表。
If you want to read and store the whole content of your file in an array, you can do this in this simple way, though there are also other ways:如果您想读取文件的全部内容并将其存储在一个数组中,您可以通过这种简单的方式执行此操作,但还有其他方式:
while( ( c = getc(file) ) != EOF )
buffer[i++] = c;
where buffer
is an char
array of 1000 elements
(it could be any number, you want), c
is a char
, and i
is an int
initialized with 0
.其中buffer
是1000 elements
的char
数组(可以是任何数字,你想要), c
是一个char
, i
是一个用0
初始化的int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.