-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:

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

Not that I advocate the use of gets or blindly appending to buffers without first checking the size, but this is basically what you need to do.


Additional problems:

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

The gets() function is inherently unsafe. 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.

Community
  • 1
  • 1
paxdiablo
  • 814,905
  • 225
  • 1,535
  • 1,899
  • 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