开发者

C: Error opening file from string name

Edited: how can i save the first string and then use the strcat func

void *threads_sorting (void *arg) {
 struct args_sort *mydata;
 mydata = (struct args_sort *) arg;

 FILE *forig
 char *file_name;

 //file_name = (char*)malloc( sizeof(char) * 10 ); 
 file_name = mydata->fname;
 printf ("File Name: %s\n", file_name);

 char *final_name;
 //final_name = (char*)malloc( sizeof(char) * 20 ); 
 final_name = file_name;
 final_name = strcat(final_name, ".sorted");
 printf ("File Name: %s\n", file_name);
 printf ("FInal Name: %s\n", final_name);

 forig = fopen开发者_Go百科(file_name,"r");
   if(forig==NULL)
 {
   printf("Unable to open file\n");
   exit(1);
 }
}//end of function

Now the output is:

File Name: arch1.txt
File Name: arch1.txt.sorted //that's why it doesn't open
Final Name: arch1.txt.sorted
Unable to open file

The question is how can i save the first string and then use strcat, my bad.


Leave out the whole malloc() code. Not only does your code leak memory, but the variable doesn't hold your filename.

This should work:

forig = fopen(mydata->fname,"r");


strcat() doesn't allocate a new string, it appends the second ".sorted" string to the first. The return value of strcat() will be the same string pointer as the first string parameter. Your usage of strcat() was mostlikely corrupting memory by writting beyond the end of mydata->fname.

See the code below for an example of how to allocate a new string for final_file.

#define FILE_SORTED_EXT ".sorted"
void *threads_sorting (void *arg) {
 struct args_sort *mydata;
 mydata = (struct args_sort *) arg;

 FILE *forig
 char *file_name;
 char *final_name;

 file_name = mydata->fname;
 printf ("File Name: %s\n", file_name);

 // Allocate space for "sorted" file_name.
 final_name = malloc(strlen(file_name) + strlen(FILE_SORTED_EXT) + 1);
 // append .sorted extentsion to file name.
 strcpy(final_name, file_name);
 strcat(final_name, FILE_SORTED_EXT);

 printf ("File Name: %s\n", file_name);
 printf ("FInal Name: %s\n", final_name);

 forig = fopen(file_name,"r");
 if(forig==NULL)
 {
   free(final_name); // make sure to cleanup allocated memory.
   perror("threads_sorting(): Unable to open file\n");
   exit(1);
 }
 // TODO: do something with forig FD and final_name.

 free(final_name); // make sure to cleanup allocated memory.
}//end of function


Check errno to get the reason for the failure. See the fopen(3), open(2), and malloc(3) man pages for the possible values.


This isn't the cause of the error, but this code doesn't do what you think it does:

char *file_name;
file_name = (char*)malloc( sizeof(char) * 10 ); 
file_name = mydata->fname;


Make sure that the file you are trying to open is in current working directory. What happens if you use the full path to the file?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜