Trying to open directory defined file in C, but file will not open. This is a sm
ID: 3690892 • Letter: T
Question
Trying to open directory defined file in C, but file will not open.
This is a smaller part of a larger project.
The user needs to be able to enter a file location to open a .txt file that is somewhere in the computer. This is the code I have for that part. Everytime I enter the directory location, the file failes to open, and makes the program run in an infinate loop. What is wrong with it?
Right now, the function is inside a case statement, because the file definition is a part of a larger more complex menu, but later I will be putting it in its own function. And my professor wants us to use pointers for the file opening.
If it makes a differnce, I am using Xcode on a mac.
case 2:
//display file location and files being used
{
int time, dia, syst;
char filename[100];
printf ("Enter the path of your data file =>");
fflush( stdout );
scanf( "%s", filename );
FILE *BP1= fopen( filename, "r" );
if ((BP1= fopen( filename,"r")) == NULL)
{
puts("ERROR OPENING FILE");
exit ( EXIT_FAILURE );
}
fscanf(BP1, "%d , %d , %d", &time, &dia, &syst);
printf("%d %d %d", time, dia, syst);
fclose(BP1);
}
break;
Explanation / Answer
C File I/o you need to use a FILE pointer, which will let the program keep track of the file being accessed.
FILE *BP1;
{
int time, dia, syst;
char filename[100];
printf ("Enter the path of your data file:");
fflush( stdout );
scanf( "%s", &filename ); //use & befor ethe filname
FILE *BP1= fopen( filename, "r" ); // read mode
if (BP1 == NULL)
{
puts("ERROR OPENING FILE");
exit ( EXIT_FAILURE );
}
fscanf(BP1, "%d , %d , %d", &time, &dia, &syst);
printf("%d %d %d", time, dia, syst);
fclose(BP1);
}
break;
I made small changes in the above code please see and use .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.