0

In my C program I am calling the shell command "find . -name \"*.bin\"" using the following code:

FILE *fptr = popen("find . -name \"*.bin\"", "r");

Now I want to open each file this command finds in order to read the data from this file. I have tried with the following way but it isn;t working:

int numbers[5];
int i = 0;
char files[1000];
FILE *ptr;
FILE *fptr = popen("find . -name \"*.bin\"", "r");
while ( fgets(files, 1000, fptr) != NULL)
{
ptr = fopen(files, "r");
fscanf(ptr, "%d", &numbers[i]);
i++;
}

How can I manage this? I would really appreciate any help!

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

1 Answers1

2

the fgets(files, 1000, fptr) commands reads the line and unless the line is too long or this is the last line without linefeed, files contains a newline.

Trying to open files fails because the filename has an extra newline. Since you're not checking if your file handle isn't NULL, you're not able to see that.

I would remove it safely like this (more techniques here: Removing trailing newline character from fgets() input, the strcspn looks better for instance):

int l = strlen(files);
if ((l>0) && (files[l-1]=='\n'))
{
  files[l-1] = '\0';
}

then

ptr = fopen(files, "r");
if (ptr == NULL)
{
   // should not happen, but still...
   fprintf(stderr,"cannot open %s\n",files);
   exit(1);
}
fscanf(ptr, "%d", &numbers[i]);

Also don't forget to call pclose(fptr); when the loop ends to account for process termination & close the pipe (and if needed get the return code from the find command).

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 2
    It is more succinct (no edge cases) to use `files[strcspn(files, "\n")] = '\0';` to replace the newline with a null byte. – Jonathan Leffler Nov 27 '17 at 20:49
  • @JonathanLeffler you're right, I'm not familiar with those. I'm going to link with an answer which does that better (this was a "from memory" attempt to provide a fix, but it took me several edits :)) – Jean-François Fabre Nov 27 '17 at 20:50
  • Both ways worked perfectly in my case. Thank you very much! –  Nov 27 '17 at 21:03