[英]How do I use a .txt file as a command line input in such a way that its contents are read as command line input in C?
[英]How do i read a .txt line by line in C?
我已经阅读了有关此内容的所有内容,但仍然没有弄清楚如何执行此操作。 我正在尝试逐行读取.txt并将其放入数组中。 我认为我的代码还可以,但是当我尝试打印数组时,它不允许我这样做。
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
int main(){
char s[20],*list[196][20];
int i;
FILE *lista;
lista=fopen("lista.txt","r");
i=0;
while(feof==0){
getline(list[i],0,lista);
i=i+1;
printf("%s\n",list[i]);
}
for(i=0;i<195;i++){
//printf("%s\n",list[i]);
}
fclose(lista);
}
之所以有两张照片是因为我尝试了两种方式来查看是否可以修复它。 我在做什么错的任何想法吗? 我得到的错误是“格式'%s'期望类型为'char *'的参数,但参数2具有类型为'char **'的参数
您将列表声明为char指针数组20的数组196的原因是什么? 该代码似乎更可靠。
int main ( void )
{
static const char filename[] = "lista.txt";
FILE *file = fopen ( filename, "r" );
char list[196][20];
int i = 0;
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
strcpy( list[i], line ); /* copy the line into list */
fputs ( line, stdout ); /* write the line */
++i;
}
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}
您的代码有几个问题。
首先,您使用的是getline()
错误。 通过传递固定大小的数组元素的地址和其大小为零, getline()
可能会尝试重新分配指针realloc()
,而这行不通。
只要文件中有足够的行,这将起作用:
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
int main(){
char *list[196];
size_t bytes[196];
FILE *lista;
lista=fopen("lista.txt","r");
if ( null == lista )
{
return( -1 );
}
// while(feof==0) is *so* wrong...
for ( int i = 0; i < 196; i++){
list[i] = NULL;
bytes[i] = 0;
// note that the address of list[i] and bytes[i] are
// passed - if you examine them after the call, you'll
// see they changed value. Since C is pass-by-value,
// the address must be passed to allow the variable in
// main to be modified by the getline() call
ssize_t bytes_read = getline(&list[i],&bytes[i],lista);
if ( bytes_read <= 0 )
{
break;
}
printf("%s\n",list[i]);
}
fclose(lista);
return(0);
}
而while(feof==0)
在许多级别上都是错误的。 裸feof
计算结果为feof()
函数的地址 ,并且永远不会等于零。 假设您的意思是while (feof(lista)==0)
,那也是错误的。 请参见为什么“ while(!feof(file))”总是错误的? 为什么。
用您的方法尝试……
#include<stdio.h>
#include<stdlib.h>
#define MAX_LINES_NO 4096
int main(){
char *list[MAX_LINES_NO];
int i = 0;
FILE *lista;
lista=fopen("lista.txt","r");
size_t len = 0;
for(i=0; i< MAX_LINES_NO; ++i) list[i] = 0;
i=0;
while(-1 != getline(&list[i],&len,lista)){
printf("%s\n",list[i]);
++i;
}
for(i=0; i< MAX_LINES_NO; ++i) free(list[i]);
fclose(lista);
}
用这种方法,您可以更改MAX_LINES_NO以动态分配指针数组。 请注意,当buffer和len为0时,此方法依赖于getline特定的行为(它动态分配内存: http : //man7.org/linux/man-pages/man3/getdelim.3.html )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.