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.
Thank you for any assistance.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; }



LinkBack URL
About LinkBacks


