Hi, I am writing a program to extract names of all the classes in a particular directory. I have to search all the files in a directoy for the same. The program compiles well, but problem occurs while running it. It says 'can't open a file XX' and 'not enough memory'. I am using Turbo C. Please help me to know where I am doing wrong. The code is as below: Code: #include <dirent.h> #include <stdio.h> #include <stdlib.h> #include<conio.h> #define BUF_SIZE 10 #define MAX_NUM 20 void scandir(char *dirname) { DIR *dir; struct dirent *ent; int i,flag=0; char string[BUF_SIZE]; char file_nm[BUF_SIZE]; char *name1="class"; char *names[MAX_NUM]; FILE *ptr; printf("Open a directory '%s':\n",dirname); if ((dir = opendir(dirname)) == NULL) { perror("Unable to open directory"); exit(1); } while ((ent = readdir(dir)) != NULL){ printf("%s\n",ent->d_name); if((strcmp(ent->d_name,".")==0) ||(strcmp(ent->d_name,"..")==0)) { } else{ if((ptr = fopen(ent->d_name, "rt")) == NULL) { perror("Cannot open the file \n"); } else { // printf("File opened successfully for reading\n"); while(!feof(ptr)) { fscanf(ptr,"%s", string); if(flag==1) { flag=0; printf("%s\n",string); } else{ if(strcmp(name1,string)==0){ flag=1; } } }//end of while } fclose(ptr); }//else }//end of outer while if (closedir(dir) != 0) { perror("Unable to close directory"); } }//end of function scandir void main() { clrscr(); scandir("c:/tc/bin/folder"); // exit(0); getch(); }
First your BUFF_SIZE is too small. In 16 bit DOS the file names are 8 characters and the file extensions are 3 characters so you have 8 + 3 = 9 plus the '.' = 10 plus the end of string character = 11. So that would mean the BUFF_SIZE should be at least 11. However I would set this much higher. Also you are searching a directory then opening every file for reading, then scanning through the file for the string "class". However you will probably run into problems because the directory you are using may have binary files (.obj, .exe). You should probably only be looking at .h and .c .cpp files. Jim