Friday 18 February 2011

Accessing the File Name in Directory Using c

This code below is used to access the filename of a directory in windows. I write the code in Microsoft Visual Studio 2008. The steps are below:
  1. Create a new Win32 Console Aplication project (File->New->Project->Visual C++ -> Win32 ->Win32 Console Application)
  2. Change the Character Set to Use Multi-Byte Character Set (Project properties -> Configuration Properties ->General -> CharacterSet : UseMulti-Byte Character Set)
  3. Write the code here, this code is used to list the name file in the directory image.
/**********************************accessingdirectory.cpp****************************************/

#include "stdafx.h"
#include
#include

struct flist
{
int num_entries;
int max_entries;
WIN32_FIND_DATA *files;
};


int main()
{

char *root="Image";
flist list = { 0, 0, NULL };
HANDLE h;
WIN32_FIND_DATA info;
int i;
FILE *listfile;
char path[200];


sprintf (path,"%s\\*.*",root);
// build a list of files
//h = FindFirstFile("*.*", &info);

h = FindFirstFile(path, &info);
if (h != INVALID_HANDLE_VALUE)
{
if ((listfile = fopen ("listfile.txt", "w")) == NULL)
{ perror ("listfile.txt"); exit (1); }
do
{
if (!(strcmp(info.cFileName, ".") == 0 || strcmp(info.cFileName, "..") == 0))
{
printf ("%s", info.cFileName);
fprintf(listfile,"%s\\%s\n",root,info.cFileName);
}
} while (FindNextFile(h, &info));
if (GetLastError() != ERROR_NO_MORE_FILES)
printf ("\nERROR_NO_MORE_FILES");
FindClose(h);
fclose(listfile);
}
else
{
printf("\nINVALID_HANDLE_VALUE");
}

// SetCurrentDirectory("Image");

return 0;
}

/******************************************************************************/