Hello ,
When im trying to compile this code it goes well,but when i run the prog i just get a flash of the cmd ,please can you tell me what i doing wrong?-im using the compailer of dev c++

#include <stdio.h> 
#include <stdlib.h> 
#define _WIN32_WINNT 0x0501 
#include <windows.h> 
#define BUFSIZE MAX_PATH 
int main(int argc, char *argv[]) 
{ 
   WIN32_FIND_DATA FindFileData; 
   HANDLE hFind = INVALID_HANDLE_VALUE; 
   DWORD dwError; 
   LPSTR DirSpec; 
 
   DirSpec = (LPSTR) malloc (BUFSIZE); 
 
   if(argc != 2) 
   { 
      printf("Uso: Test <dir>\n"); 
      return 2; 
   } 
   printf ("Directorio elegido: %s\n\n", argv[1]); 
   strcpy(DirSpec, argv[1]); 
   strcat(DirSpec, "\\*"); 
   // Buscamos el primer fichero del directorio 
   hFind = FindFirstFile(DirSpec, &FindFileData); 
   if (hFind == INVALID_HANDLE_VALUE) 
   { 
      printf ("Handle incorrecto. Error: %u.\n", GetLastError()); 
      return (-1); 
   } 
   else 
   { 
      printf ("Primer fichero: %s\n\n", FindFileData.cFileName); 
 
      // Listamos todos los ficheros del directorio 
      while (FindNextFile(hFind, &FindFileData) != 0) 
      { 
         printf ("Siguiente fichero: %s\n\n", FindFileData.cFileName); 
      } 
 
      dwError = GetLastError(); 
      FindClose(hFind); 
      if (dwError != ERROR_NO_MORE_FILES) 
      { 
         printf ("Error en FindNextFile: %u.\n", dwError); 
         return (-1); 
      } 
   } 
   free(DirSpec); 
   return (0); 
}

Recommended Answers

All 27 Replies

you need to add a line before the return to make the program stop so that you can read it. This will do ok

system("PAUSE");

Also, it isn't necessary to create a new thread just to correct a mistake. Just hit the Edit button -- you have about 5 minutes or so to make corrections that way.

you need to add a line before the return to make the program stop so that you can read it. This will do ok

system("PAUSE");

Except that the statement isn't in the least bit portable...

Much better alternative:

cin.get();

Except that the statement isn't in the least bit portable...

Much better alternative:

cin.get();

That not being the point since the code is already using Windows specific functions (windows.h).

A good reason not to write system("pause") would be because it spawns a seperate process and troubles the OS since its a system level function. Why incur such overhead when the same can be done with getchar( ) .


A good reason not to write system("pause") would be because it spawns a seperate process and troubles the OS since its a system level function. Why incur such overhead when the same can be done with getchar( ) .

Because in such a trivial program it doesn't make a hill of beams which way its coded. Creating another process is also trivial in most of today's computers; the os would barely even know the process is present in the system.

Because in such a trivial program it doesn't make a hill of beams which way its coded. Creating another process is also trivial in most of today's computers; the os would barely even know the process is present in the system.

All this is true, but aren't we forgetting that we should me modelling standard practices, so we don't have to retrain them 2 weeks later?

Thanks-it help,
I have other problem :
i need to open the first file and to read from it, but i get an error when im trying to open the file what should i do?
I need to open the file "FindData.cFileName" ann to read from it,how can i open it?

post code -- we can't see your monitor. Is that file in current working directory? If not you will have to add the full path to the file.

i have reduced the code so now it look like this:

int main()
{
HANDLE hFind;
WIN32_FIND_DATA FindData;
// Find the first file
hFind = FindFirstFile("C:\\temp\\*.*", &FindData);
/*file process*/
cout << FindData.cFileName << endl;
// Look for more
while (FindNextFile(hFind, &FindData))
{
/*file process*/
cout << FindData.cFileName << endl;
}
// Close the file handle
FindClose(hFind);
return 0;
}

no i reduced the code so now it look like this:

int main()
{
    HANDLE hFind;
    WIN32_FIND_DATA FindData;
   // Find the first file
    hFind = FindFirstFile("C:\\temp\\*.*", &FindData);
/*file process*/
    cout << FindData.cFileName << endl;
// Look for more
    while (FindNextFile(hFind, &FindData))
    {
        /*file process*/
       cout << FindData.cFileName << endl;
    }
// Close the file handle
    FindClose(hFind);
    return 0;
}

I dont succed to open the first file

Thanks for the quick reply

If it succeeds, FindFirstFile() puts the filename of the first file into the structure. Your program is tossing that out by immediately calling FindNextFile(). I use a do loop here instead of a while loop

hFind = FindFirstFile("C:\\temp\\*.*", &FindData);
/*file process*/
cout << FindData.cFileName << endl;
// Look for more
do {
  //check for . and ..
  if( strcmp(FindData.cFileName,".") != 0 &&
        strcmp(FindData.cFileName,"..") != 0)
  {
       // do something
  }
} while( FindNextFile(...) );

Please can you explain me how can i open the first file found and later the second...

Thaks again

Do it inside that if statement which is inside the do loop, something like this:

do {
  //check for . and ..
  if( strcmp(FindData.cFileName,".") != 0 &&
        strcmp(FindData.cFileName,"..") != 0)
  {
        ifstream in(FindData.cFileName);
        // do something with this file
        //
        // now close the file
        in.close();
        in.clear();
   }

Thanks again for replying, the file dosent open
i added the include file <ifstream> but i get the error "no such file or directory"
im not so familiar in c++ code usually i use c language
can you explain your steps Or pass it to C

Thanks ahead

Ok here's the same thing in C

do {
  //check for . and ..
  if( strcmp(FindData.cFileName,".") != 0 &&
        strcmp(FindData.cFileName,"..") != 0)
  {
        FILE* fp = fopen(FindData.cFileName,"r");
        // do something with this file
        //
        // now close the file
        fclose(fp);
        fp = 0;
   }

Thanks again,
but this dont work ,when im tryiing to open the file i get my error message
If (fp==NULL)
printf("ërror");


is it working for you?

Thanks again,
but this dont work ,when im tryiing to open the file i get my error message
If (fp==NULL)
printf("ërror");


is it working for you?

Then you're doing something wrong. I think it's on line 10... :confused:

Thanks for keeping on answearing!

i get the list of all my file-so it work well,but when i try to open the first one i get my error message.

Any ideas

what error message do you get?

This is my error mesage from the code

If (fp==NULL)
printf("error");

you need to repost your code so we can see what you have done.

as you asked

#include "stdafx.h"
#include <windows.h> 
#include <iostream> 
#include <fstream> 
using namespace std;
int main()
{
    HANDLE hFind;
    WIN32_FIND_DATA FindData;
    FILE *fp;
 //std::ifstream in;
    cout << "A very basic FindFirst/Next demo.\n" << endl;
// Find the first file
    hFind = FindFirstFile("C:\\Test\\*.*", &FindData);
 
 
 if( strcmp(FindData.cFileName,".") != 0 && strcmp(FindData.cFileName,"..") != 0)
   
  {
      fp = fopen(FindData.cFileName, "r");
 if(fp==NULL)
   cout << "problem open file" << endl;
 char c;
 c=fgetc(fp);/*Reading of file character by charactercommences here*/
    
 while (c!=EOF)
 {
 
  cout << "Im in\n" << endl;
         c=fgetc(fp);
         printf("charcteres d% \n",c);
 }
 
  
   }
 
while (FindNextFile(hFind, &FindData))
    {
        if( strcmp(FindData.cFileName,".") != 0 && strcmp(FindData.cFileName,"..") != 0)
   
      {
        fp = fopen(FindData.cFileName, "rt");
  if(fp==NULL)
    cout << "problem abrier fichero" << endl;
 
  c=fgetc(fp);/*Reading of file character by charactercommences here*/
    
  while (c!=EOF)
  {
          cout << "Im in\n" << endl;
          c=fgetc(fp);
          printf("charcteres d% \n",c);
  }
      }
  cout << FindData.cFileName << endl;
    }
// Close the file handle
    FindClose(hFind);
   
   return 0;
}

your program never closes the file (never calls fclose() ). There is a finite number of files that can be open at the same time -- years ago the limit was 20, but MS-Windows is a lot more.

why are you mixing c and c++ code? If you are writing a c++ program you should probably use c++ fstream, not C FILE. Also should not mix cout and printf(), use just one or the other for consistency.

You can greatly reduce the amount of code you have by using a do loop instead of a while loop as I illustrated later. Right now it looks like you have everything coded twice, which isn't necessary with a do loop.

as to your question why it can not open the file: Probably because the current working directory is NOT in "c:\test". Is that the directory where the *.exe program is located? If not (and probably not) then you have to add the full path to the file name. FindFile() does not do that -- it only returns file names with no path information. Something like this:

char filename[_MAX_PATH];

...
strcpy(filename,"c:\\test\\");
strcat(filename, FindData.cFileName);
fp = fopen(filename, "rt");

Thnaks again for responding and insisting to help
about the close file you are right-i didnt put it due to testing fase
about mixing c and c++ you are right,i know c and not c++ but i tried with c++ because i got answeared in c++.

It seem that you are right i succed to open the file,now only left is to use your advise of the DO LOOP
and to correct the things
Thanks Alot !!!

Thanks - i have succed to open the files ,but how can i open a directory found in a given directory,the idea is : im looking to open all the files and the directoris which i found under a given inicial directory ,and process all the files which i have found?

[/B]
my code right now is:

#include "stdafx.h"
#include <windows.h> 
#include <iostream> 
#include <fstream> 
using namespace std;

int main()
{
    HANDLE hFind;
    WIN32_FIND_DATA FindData;
    FILE *fp;
	char filename[_MAX_PATH];
	char c;
	int x=0;


   printf("testing \n");

  
// Find the first file

    hFind = FindFirstFile("C:\\test\\*.*", &FindData);
	
    	printf(FindData.cFileName);
	printf("\n");
	  
	// Look for more
  
while (FindNextFile(hFind, &FindData))
    {
        if( strcmp(FindData.cFileName,".") != 0 && strcmp(FindData.cFileName,"..") != 0)
	  
			{
				
                printf(FindData.cFileName);
				strcpy(filename,"c:\\test\\");
				strcat(filename, FindData.cFileName);
				fp = fopen(filename, "rt");
				if(fp==NULL)
					printf("problem on open the file");
				x=0;
				c=fgetc(fp);/*Reading of file character by charactercommences here*/
				
				while (c!=EOF)
					{
						 //Process file						 c=fgetc(fp);
						 
		
					}
								
				fclose(fp);
			}
		
	 }

// Close the file handle

    FindClose(hFind);
	  

	  return 0;
}

you will want to use recursion to process the directories. Here is an example of how to do that.

[edit]After looking closer it will take a little bit more to port that. you will need to know about linked lists and arrays. [/edit]

Do you have somthing similar in C?

Thanks

It is C code except the vector class. Just replace vector with a 2d char array and add malloc() where needed to allocate memory for the strings. You wouldn't want to turn that in as your assignment if you have not covered recursion yet because your teacher will know the difference.

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.