kahsay.k
kahsay.k

Reputation: 61

Open and read multiple files sequentially on linux systems

I have a file named file.txt, that contains other file paths as a content. Now, am trying to open my "file.txt", read each line and load each content in the captured line, as my line is a file path. see below what my file.txt contains:

file.txt: contains

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

and,

/Desktop/path1.txt:contains

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

/Desktop/path2.txt:contains contents like..

abcd
efg
jshdjsdd

Then finally,as explained above, i want to:

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.

take a look at my work:

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);
}

the problem is, when i run my main.cpp, it says FILE...not found, from void load_data_path(char *data_path) function. and segfault when i remove exit(EXIT_SUCCESS);

Any suggestion? thanks.

Upvotes: 0

Views: 478

Answers (2)

Robert Kock
Robert Kock

Reputation: 6028

Please remind that the function getline() does not remove the newline character. When the load_parent_path function calls load_data_path it therefore passes a filename that includes the newline.

Upvotes: 1

David Ranieri
David Ranieri

Reputation: 41026

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null- terminated and includes the newline character, if one was found.

You can remove the trailing newline using:

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

Upvotes: 1

Related Questions