fopen in plain c

Our teacher is making us write code in plain c instead of C++.. The user is to input a file name and then the program is supposed to open the file out put the full file then close.. so i have this.

1
2
3
4
5
6
7
8
9
FILE *fp;
char mystring[100];

fp = fopen("readme.txt","r");
if(fp == NULL)
     printf("cant open this file\n");
fgets (mystring, 100, fp);
puts(mystring);
fclose(fp);


and that worked.. however that doesnt give the ability for the user to input their file name.. so im trying this..

1
2
3
4
5
6
7
8
9
10
11
12
13
char buf[BUFSIZ];
FILE *fp;
char mystring[100];
char *str;
              
str = buf;    
printf("Buf: %s\nstr: %s\n",buf, str); /*testing purposes*/
fp = fopen(str,"r");
if(fp == NULL)
     printf("cant open this file\n");
fgets (mystring, 100, fp);
puts(mystring);
fclose(fp);


i keep getting cant open file when done this way.. but for my test line.. both buf and str output readme.txt. im kind of lost on what to do

anybody have any ideas?

edit: this is actually a server of a client/server program. i am pulling buf in with
read (fd, buf, sizeof buf);
and i just realized when i print out buf it has a \n char at the end. maybe thats why the file isnt being found? how would i get rid of this \n char?

edit2: SOLVED! instead of using fgets to pull in buf from the user.. i used scanf. seems to work fine.
Last edited on
Topic archived. No new replies allowed.