Technical inquiries on C.

Technical inquiries on C.

Post by xTractatorix on Sat Jun 23, 2012 7:28 pm
([msg=67491]see Technical inquiries on C.[/msg])

Alright so, as stated above i have some inquiries on C. Ive made a simple C program that opens a .txt file on my desktop, and i wanted to expand on the program by allowing the user to enter in what file on the desktop he/she wants to open by typing it on the screen, ive come across some problems though... Any help would be appreciated.

char filename [20] = {'\0'};
printf("What is the filename you wish to open?");
scanf("%s",filename);
FILE *file = fopen("C:\\Users\\Ricardo\\Desktop\\%s.txt", filename ,"r");

As you can see i attempted to do this by, making a char array, storing the user inputtharray, andthen injecting the string in the fopen function.Whenever i try this though it just says to many arguments in fopen.
xTractatorix
Experienced User
Experienced User
 
Posts: 61
Joined: Sun May 13, 2012 8:42 am
Blog: View Blog (0)


Re: Technical inquiries on C.

Post by 0phidian on Sat Jun 23, 2012 8:14 pm
([msg=67493]see Re: Technical inquiries on C.[/msg])

Since fopen only takes 2 arguments you could try using string concatenation instead of format strings.

Code: Select all
#include <stdio.h>
#include <string.h>

int main(){
   char filename [20];
   printf("What is the filename you wish to open?");
   scanf("%s",filename);
   char path[40];
   strcat(path,"C:\\Users\\Ricardo\\Desktop\\");
   strcat(path, filename);
   FILE *file = fopen(path, "r");
   fclose(file);
return 0;
}

You also might want to validate the input to prevent a buffer overflow and catch exceptions in case an invalid filename is given.
User avatar
0phidian
Poster
Poster
 
Posts: 245
Joined: Sat Jun 16, 2012 7:04 pm
Blog: View Blog (0)



Return to C and C++

Who is online

Users browsing this forum: No registered users and 0 guests