Hi!
I have to make a program, wich lists all files in current dir, and then save all file names into an array.
My program doesn't work ! Can you tell me why?
Thanks a lot:)

#include <dirent.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h>
#include <dirent.h>
int main(void)
{ FILE *fp;
  DIR           *d;
  struct dirent *dir;
  char *filenames[20];
  int i=0;
  int k,l;
  d = opendir(".");
  if (d)
  {
  
    while ((dir = readdir(d)) != NULL)
    {
      
      filenames[i]=(dir->d_name);
      printf("%d",i);
      printf(filenames[i]);
      printf("\n");
      i++;
      
    }

    closedir(d);
  }
  printf(filenames[3]);
 
 
// *filenames[i]='\0';
  system ("pause");
  return(0);
Member Avatar for iamthwee

>char *filenames[20];

And what happens if you have more than 20 files there?

>char *filenames[20];

And what happens if you have more than 20 files there?

I don't know how to make it to work for unspecified number of files:)

Hi!
I have to make a program, wich lists all files in current dir, and then save all file names into an array.
My program doesn't work ! Can you tell me why?

You need to tell us why you think it's wrong? We don't know the symptoms you're seeing.

One thing I notice though is you are not saving the file name correctly. Once you read the second file, the first name is gone. You need to move the entire name into your list, not just the pointer. Be sure you redefine filenames so it can hold the string properly.

You need to tell us why you think it's wrong? We don't know the symptoms you're seeing.

One thing I notice though is you are not saving the file name correctly. Once you read the second file, the first name is gone. You need to move the entire name into your list, not just the pointer. Be sure you redefine filenames so it can hold the string properly.

Yes this is the problem,thanks a lot :)

One thing I notice though is you are not saving the file name correctly. Once you read the second file, the first name is gone. You need to move the entire name into your list, not just the pointer. Be sure you redefine filenames so it can hold the string properly.

Could you please explain to me how this is done? I wanted to save some file names into an array so I could manipulate the text in the files, but I can't get past this problem and I have tried to save the entire name in the array but I continually get casting messages and segmentation faults. It runs as is, but the array only contains the last file name. I'm using the same program from above...

Only if you'll bother to read The Rules as requested when you registered, and the post entitled Read Me: Read This Before Posting. Also, please tell us what we could have done to express the importance of reading the rules first?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.