Bow
Bow

Reputation: 455

Regarding FOPEN in C

I am having a problem regarding FOPEN in C.

I have this code which reads a particular file from a directory

FILE *ifp ;
char directoryname[50];
char result[100];
char *rpath = "/home/kamal/samples/pipe26/divpipe0.f00001";
char *mode = "r";

ifp = fopen("director.in",mode); %director file contains path of directory

while (fscanf(ifp, "%s", directoname) != EOF) 
 {
 strcpy(result,directoname);  /* Path of diretory /home/kamal/samples/pipe26 */
 strcat(result,"/");          /* front slash for path */
 strcat(result,name);         /* name of the file divpipe0.f00001*/
 }

Till this point my code works perfectly creating a string which looks " /home/kamal/samples/pipe26/divpipe0.f00001 ".

The problem arises when I try to use the 'result' to open a file, It gives me error. Instead if I use 'rpath' it works fine even though both strings contain same information.

 if (!(fp=fopen(rpath,"rb")))     /* This one works fine */
  {
    printf(fopen failure2!\n"); 
    return;
 }


  if (!(fp=fopen(result,"rb")))     /* This does not work */
  {
    printf(fopen failure2!\n"); 
    return;
  }

Could some one please tell why I am getting this error ?

Upvotes: 0

Views: 228

Answers (2)

Homer
Homer

Reputation: 99

The error is the array 'char* result[100]', here you are allocating an array of 100 pointers to strings, not 100 bytes / characters, which was your intent.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234875

I think you mean char result[100];; i.e. without the asterisk. (Ditto for directoryname.)

You're currently stack-allocating an array of 100 pointers. This will not end well.

Note that rpath and mode point to read-only memory. Really you should use const char* for those two literals.

Upvotes: 1

Related Questions