Can I use a variable in the fopen function. Here's the code:
int x = 0;
char textDoc[255];
printf("Please enter the name of your file. Be sure to include the file extension.");
while (!(textDoc[x-1] == 't' && textDoc[x-2] == 'x' && textDoc[x-3] == 't' && textDoc[x-4] == '.') && x < 255)
{
textDoc[x] = getchar();
x = x + 1;
}
printf("%s", textDoc);
tdPtr = fopen(textDoc, "r");
When I manually enter the name of the document into the fopen function, it opens fine.
However when I type it into the textDoc variable as I'd like the program to function, it doesn't open. I know that I entered the correct document name because I printed the contents of textDoc to the screen.
How can I get the file for which the user enters the name, to open?
while (!(textDoc[x-1] == 't' && textDoc[x-2] == 'x' && textDoc[x-3] == 't' && textDoc[x-4] == '.') && x < 255)
I think you meant the following:
int x = 0;
while ((textDoc[x++] = getChar()) != '\n')
;
textDoc[x - 1] = '\0';
THEN check for .txt and do anything else you want, but you have to get the whole string first! You just can't start validating my (i.e. the user's) input before I'm even done entering it. I don't know whether or not that's contributing to the error you're seeing, but it's definitely worth fixing.