Storing filenames in an array

This is a discussion on Storing filenames in an array within the C Programming forums, part of the General Programming Boards category; Hi, I'm making a program, which reads the filenames from a directory, and stores them in an array of strings, ...

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    11

    Storing filenames in an array

    Hi,
    I'm making a program, which reads the filenames from a directory, and stores them in an array of strings, but when I'm running the program, it stores only 1 filename 20 times in the whole array.

    Here's my code:

    Code:
    #include <stdio.h>
    #include <dirent.h>
    
    int main(void)
    {
    	char *NameArr[20]; // the array which will store the filenames
    	DIR *dir;
    	int i=0,k;
    	struct dirent *ent;
    	dir = opendir ("c:\\");
    	if (dir != NULL) 
    	{
    	/* print all the files and directories within directory */
    	while ((ent = readdir (dir)) != NULL) 
    		{
    		NameArr[i]=ent->d_name;
    		/* save filenames in the array */
    		i++;
    		}
    	closedir (dir);
    	} 
    	else 
    	{
    	/* could not open directory */
    	perror ("");
    	}
    	for (k=0;(k<(i+1)) && (k<20);k++) printf("%s\n",NameArr[k]);
    	//print the filenames on the screen
    	return 0;
    }
    Thank you for any help!

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,045
    Code:
    char *NameArr[20]; // the array which will store the filenames
    What you have here is an array of 20 pointers. The trouble is that readdir() uses a static dirent structure internally (or so it would seem), so that each time you call it, it overwrites its internal data structure and returns a pointer to the same structure. You assign NameArr[i] to ent->d_name and continue. The trouble is that ent->d_name gets overwritten with each call.

    Basically, you need to copy the data yourself rather than point at the data which readdir() owns and thus can change if it likes. The simplest way would be to use
    Code:
    char NameArr[20][256];  // ugh, hard-coded max file length
    and then
    Code:
    strcpy(NameArr[i], ent->d_name);
    I'd really malloc() the data, though, so you don't have to worry about file names being too long.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Aug 2010
    Posts
    11
    Now it doesn't do anything, or it exits with a windows error message.

    Code:
    #include <stdio.h>
    #include <dirent.h>
    #include <string.h>
    
    int main(void)
    {
    	char NameArr[20][256];
    	DIR *dir;
    	int i=0,k;
    	struct dirent *ent;
    	dir = opendir ("c:\\");
    	if (dir != NULL) 
    	{
    	/* print all the files and directories within directory */
    	while ((ent = readdir (dir)) != NULL) 
    		{
    		strcpy(NameArr[i],ent->d_name);
    		i++;
    		/* save filenames in the array */
    		}
    	closedir (dir);
    	} 
    	else 
    	{
    	/* could not open directory */
    	perror ("");
    	}
    	for (k=0;(k<(i+1)) && (k<20);k++) printf("%s\n",NameArr[k]);
    	//print the filenames on the screen
    	return 0;
    }

  4. #4
    Registered User
    Join Date
    Aug 2010
    Posts
    11
    Got it. There were more then 20 files in the directory. My first program didnt mention it, and ran smoothly.
    I will now make it with dynamic memory allocation.
    Thank you for your help.

  5. #5
    Registered User
    Join Date
    Aug 2010
    Posts
    11
    Don't wanted to make a new topic for this.
    So the program works, but if i get to the end of the list, or at the beginning, the program begins writing crazy things.
    It should jump to the end or beginning, which it does after some keypresses.
    Navigate with arrows exit with enter or esc
    Sorry for hungarian comments:P
    The code is in the attachment

    Here's the exe: cmenu.exe
    I dont have any clue why it didnt jump immediately to the other end of the list...
    Maybe you can point me out wheres the problem.
    I am pretty new to C, just came from Pascal.
    Thank you
    Attached Files Attached Files

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,788
    Didn't look all the way through the logic of your program but I saw these things of note:
    Code:
    #include <stdio.h>
    #include <dirent.h>  //könyvtárkezelés
    #include <string.h>  //stringkezelés (strcpy)
    #include <conio.h> //getch()-nak
    #include <windows.h> //színeknek
    
    ...
    
    NameArr[i]=(char *)malloc(sizeof(char)*MemSize);
    #1 You should be including the stdlib header if you are using malloc.
    #2 You should not be casting the return value of your malloc call. The void pointer returned by malloc can be safely assigned to the elements of NameArr (char pointers).
    #3 sizeof(char) is guaranteed to be 1

    Combining all of that, those pieces of your program should look like:
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <dirent.h>  //könyvtárkezelés
    #include <string.h>  //stringkezelés (strcpy)
    #include <conio.h> //getch()-nak
    #include <windows.h> //színeknek
    
    ...
    
    NameArr[i]=malloc(MemSize);

    Also:
    Code:
    char *NameArr[100], ch;
    
    ...
    
    free(NameArr); //felszabadítja a lefoglalt memóriát
    #4 That is not how you free the memory for that array. You must loop through the elements and free each element(pointer) in the array individually (up to i I think?) that had a malloc'ed value assigned to it. Each call to malloc must have an accompanying call to free.

    Probably other issues but those are the ones that stood out to me.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    Registered User
    Join Date
    Aug 2010
    Posts
    11
    Thank you, all my problems are solved now.
    However, when I send the exe and the c file to my friend, the exe wont run, and the c file wont compile (many errors) by him...
    What could be the problem?

  8. #8
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,788
    Well, what compiler/OS do you have and what compiler/OS does your friend have? Some of the code you have in your program could be compiler/OS specific (I'd be suspicious about the dirent stuff). Also, what are your friends errors.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  9. #9
    a guy with long hair Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    103
    What compilers are you both using? What errors does he get? Did you compile with highest level of warnings and "pedantic mode"? Did he?
    Ah, hk_mp5kpdw, you got me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Storing Cstrings in an Array
    By Tien1868 in forum C Programming
    Replies: 4
    Last Post: 07-09-2009, 07:48 PM
  2. Storing values from Edit Box into an array
    By E_I_S in forum C++ Programming
    Replies: 10
    Last Post: 06-05-2008, 06:24 AM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. Storing multiple string in array
    By winsonlee in forum C Programming
    Replies: 2
    Last Post: 03-15-2004, 06:49 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21