在Linux系统上按顺序打开和读取多个文件

时间:2016-03-01 08:01:39

标签: c linux fopen

我有一个名为file.txt的文件,其中包含其他文件路径作为内容。现在,我正在尝试打开我的" file.txt",读取每个line并加载捕获行中的每个内容,因为我的行是文件路径。请参阅下面file.txt包含的内容:

file.txt:包含

/Desktop/path1.txt
/Desktop/path2.txt

和,

/Desktop/path1.txt :包含

something...is here in this line
do you have you iurgiuwegrirg
ewirgewyrwyier
jhwegruyergue

/Desktop/path2.txt :包含类似..

的内容
abcd
efg
jshdjsdd

最后,如上所述,我想:

1.open file.txt
2.read each line, here line is a path
3.open line as a path,(/Desktop/path1.txt ...and /Desktop/path2.txt)
4.read contents in each path.

看看我的工作:

的main.c

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#define PATH "file.txt"

void load_data_path(char *data_path)
{
   FILE *stream;
   char *line = NULL;
   size_t len = 0;
   ssize_t read;

   stream = fopen(data_path, "r");
   if (stream == NULL)
   {
       printf("FILE..not found\n");
       exit(EXIT_FAILURE);
   }
   while ((read = getline(&line, &len, stream)) != -1) 
   {
       printf("Content in path: %s", line);
   }
   free(line);
   fclose(stream);
   exit(EXIT_SUCCESS);
}
void load_parent_path(char *init_path)
{
   FILE *stream;
   char *line = NULL;
   size_t len = 0;
   ssize_t read;

   stream = fopen(init_path, "r");
   if (stream == NULL)
   {
       exit(EXIT_FAILURE);
   }
   while ((read = getline(&line, &len, stream)) != -1) 
   {
       printf("Current path from parent file: %s\n", line);
       //pass a current line, a path to another reader function
       load_data_path(line);
   }
   free(line);
   fclose(stream);
   exit(EXIT_SUCCESS);
}

int main(void)
{
   //PATH="file.txt", this functions reads contents of file.txt
   load_parent_path(PATH);
}

问题是,当我运行我的main.cpp时,它从FILE...not found函数中显示void load_data_path(char *data_path)。我删除segfault

exit(EXIT_SUCCESS);

有什么建议吗?谢谢。

2 个答案:

答案 0 :(得分:1)

请提醒函数getline()不会删除换行符。当load_parent_path函数调用load_data_path时,它会传递包含换行符的文件名。

答案 1 :(得分:1)

  

getline()从流中读取整行,存储地址          包含文本的缓冲区为* lineptr。缓冲区为空 -          终止并包含换行符,如果找到了。

您可以使用以下方法删除尾随换行符:

char *p = strchr(line, '\n');
if (p != NULL) *p = '\0';