逐行读取C并存储在数组中

时间:2015-11-02 13:01:53

标签: c linux

我正在尝试从文件列表中读取文件名并将这些名称存储在filenames []数组中。

const int NUMBER_OF_FILES = 100;//here please define number of files listed in 
char* filenames [NUMBER_OF_FILES];//will contain all the file names in the list provided in List_of_input_files.txt

int counter=0;
FILE *inputfilelist = fopen("List_of_input_files.txt", "r");
char line[256];


  while(fgets(line, sizeof(line), inputfilelist)){

    filenames[counter]=line;    
    printf("%s counter: %d\n\n\n", filenames[counter], counter);
    counter++;
  }


//**************PROBLEM IS HERE***************

printf("\n\n\n\n%s Counter: 3 ", filenames[2]);// this is only to test what is inside this filename stored

fclose(inputfilelist);

输出结果为:

File1.txt
 counter: 0


File2.gif
 counter: 1


File3.bat
 counter: 2


File4.xml
 counter: 3


File5
 counter: 4


File6.7z
 counter: 5


File7.xlsx
 counter: 6






File7.xlsx
  Counter : 3

问题是最后一个文件Name应该是File3.bat但不知道它不是。 它始终显示最后一个文件,即File7.xlsx。

也许这是我正在做的一个愚蠢的错误,并没有清楚地看到它或某些东西。我是新手,所以我不确定。请帮忙!

它已得到改进,并且已添加了所请求的内容。

2 个答案:

答案 0 :(得分:4)

这一行

filenames[counter]=line; 

不能做你想做的事;它将line缓冲区的地址复制到filenames[counter];您filenames[i]的所有内容都指向line,因此当您打印filenames[2]时,它会将最后读到的内容打印到line

如果您要将line内容复制到filenames[counter],则需要使用malloc分配内存来保存副本或calloc然后使用strcpy复制内容(如果有,请使用strdup):

filenames[counter] = malloc( strlen( line ) + 1 );
if ( filenames[counter] )
  strcpy( filenames[counter], line );

filenames[counter] = strdup( line ); // if you have strdup available;
                                     // it's not a standard function

当您完成后,您需要free filenames[i]

或者,您可以将filenames数组声明为char的2D数组:

char filenames[NUMBER_OF_FILES][256];

直接读入数组:

fgets(filenames[counter], sizeof(filenames[counter]), inputfilelist))

答案 1 :(得分:-1)

您必须分配内存来存储多个文件名。

const int NUMBER_OF_FILES = 100;//here please define number of files listed in
const int MAX_FILE_NAME_SIZE = 50;
char filenames[NUMBER_OF_FILES][MAX_FILE_NAME_SIZE];//will contain all the file names in the list provided in List_of_input_files.txt

int counter=0;
FILE *inputfilelist = fopen("List_of_input_files.txt", "r");
char line[256];


  while(fgets(line, sizeof(line), inputfilelist))
  {

    //filenames[counter]=line;
    strcpy(filenames[counter],line);
    printf("%s counter: %d\n\n", filenames[counter], counter);
    counter++;
  }


//**************PROBLEM IS HERE***************

printf("\n\n\n%s Counter: 3 ", filenames[2]);// this is only to test what is inside this filename stored

fclose(inputfilelist);