Alexandre Lapille
Alexandre Lapille

Reputation: 69

file->d_name into a variable in C

I have a probleme with a program. I need to take file name in a folder and put it in a variable. I tried that:

#define _POSIX_SOURCE
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#undef _POSIX_SOURCE
#include <stdio.h>

int main()
{
    DIR *dir;
  struct dirent *file;
  char fileName;
  dir = opendir("../../incoming");

    while ((file = readdir(dir)) != NULL)
    printf("  %s\n", file->d_name);
    fileName = file->d_name;
    printf(fileName);
    closedir(dir);
    return 0;
}

thx

Upvotes: 2

Views: 19881

Answers (2)

A Lan
A Lan

Reputation: 425

Not very clear what you wanted, I prefer to think you want read the file name into your varible 'fileName' and then handle that varible... Correct 2 parts:

  1. fileName type should be same as the struct member for assign.
  2. the while loop......

    int main(){
      DIR *dir;
      struct dirent *file;
      char fileName[255];
      dir = opendir("../../incoming");
        while ((file = readdir(dir)) != NULL)
        {
            printf("  %s\n", file->d_name);
            strncpy(fileName, file->d_name, 254);
            fileName[254] = '\0';
            printf("%s\n", fileName);
        }
        closedir(dir);
    return 0;
    }
    

Upvotes: 3

caskey
caskey

Reputation: 12695

You need to declare a character array of sufficient size and copy the contents of the file->d_name into it if you want to save it past the call to closedir().

If you want to simply print the name,

printf("%s\n", file->d_name);

would accomplish that.

Upvotes: 1

Related Questions