-2

I have tried using the following code to pass a char into a string and to open a .txt file so i can read it's content. I have no idea why and how can i utilize this fopen to actually read test.txt

int main(){

char input[60];


char a;
FILE *file;

printf("Hello!\n");

    enter code here

printf("Pelase input a file name in .txt format: \n");
gets(input);

printf("%s",input);
printf("\n");

**file = fopen("%c,input","rt");** 

// file = fopen("%s",input) <-- Doesnt work

// file = fopen("%s",input,rt) <-- Error

if (file){

  while((a=fgetc(file))!=EOF){

        printf("%c",a);
    }
    fclose(file);


}
}
user3809384
  • 111
  • 1
  • 4
  • 10

1 Answers1

2

If you want to add ".txt" to whatever the user entered, then open that file, you can use:

gets (input);
strcat (input, ".txt");
file = fopen (input, "r");

Note that I do not advocate the use of gets, or blindly appending to buffers without first checking the size, but this is the minimum necessary change to achieve what you want. See below for why those two things are a bad idea.


Additional problems with the current code:

  • The return value from fgetc() is, and hence the type of a should be, int.

  • The gets() function is inherently unsafe, to the point where it's been removed from the standard. Use fgets() or find a safe user input function.

  • Don't ever append to buffers blindly. Like the use of gets() and certain scanf() format strings, it will allow buffer overflows in your code.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • can i know what "r" means? i have seen some samples using "w" some using "wr" and whats not – user3809384 Sep 03 '14 at 06:15
  • @user3809384: `"r"` is read only. Any good link on the net for `fopen()` should detail these. `"wr"` is short for "wrong way to do it" :-) – paxdiablo Sep 03 '14 at 06:17