-
Help with user file I/O
Hello,
I am teaching myself C, and am having difficulty writing to a user-specified file. In the code below, fopen keeps returning a null file pointer. When the file location is physically written in the code, however, the program works as expected. My question has two parts:
1) Why does fopen return a null pointer?
2) What should I change to make the program accept user-specified input files?
I have not been able to find an answer to these questions in my C book or through online searches.
Note: The code is written and compiled in Microsoft Visual C++ 2008, if that makes a difference.
Code:
#define _CRT_SECURE_NO_WARNINGS
#define MAX_FILE 100
#define MAX_TEXT 50
#include <stdio.h>
int main()
{
char file_location[MAX_FILE];
char text[MAX_TEXT];
FILE *myfile;
printf("Enter file location: ");
fgets(file_location, MAX_FILE, stdin);
myfile = fopen(file_location,"w");
//myfile = fopen("c:/c test files/test.txt","w"); //PROGRAM WORKS IN THIS CASE
if (myfile != NULL)
{
printf("Enter your text: ");
fgets(text, MAX_TEXT, stdin);
fprintf(myfile, text);
}
else
{
printf("INVALID FILE PATH.\n");
return 0;
}
fclose(myfile);
return 0;
}
Thank you for any assistance.
-
Remove the newline from your buffer after you call fgets on it.
Quzah.
-
Thank you, quzah.
For anybody's reference, here is the revised (and working!) code:
Code:
#define _CRT_SECURE_NO_WARNINGS
#define MAX_FILE 100 //maximum length of file_location string, including termination character
#define MAX_TEXT 50 //maximum length of text string, including termination character
#include <stdio.h>
int main()
{
char file_location[MAX_FILE];
char text[MAX_TEXT];
int i; //loop counter
FILE *myfile;
printf("Enter file location: "); //note: fopen doesn't like creating new directories
fgets(file_location, MAX_FILE, stdin);
for (i=0; i<MAX_FILE; i++) //replace newline character with string termination character
{
if (file_location[i] == '\n'){
file_location[i] = '\0';
}
}
printf("File location: %s\n",file_location);
myfile=fopen(file_location,"w");
if (myfile != NULL) //checks if file is valid
{
printf("Enter your text: ");
fgets(text, MAX_TEXT, stdin);
fprintf(myfile, text);
}
else
{
printf("INVALID FILE PATH.\n");
return 0;
}
fclose(myfile);
return 0;
}
-
1. your loop for replacing \n with \0 could be exitted as soon as the \n or \0 char is encountered - no sence to continue
2. using user provided string as a format for printf is a big security hole. - You should replace fprintf with fputs or use "%s" format in fprintf