Thursday, 21 November 2013

Getting File Path From The User/Adding User Entered String As Part Of A Longer String

Here is a program to get a text file path and name from the user. These are then saved as a single string into another char variable. Then the file is opened and displayed.


#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int main()
{
    char path[100],fname[100],complete[200],ch;
    FILE *fp;

    printf("Please enter the path to the text file (eg: c:\\users\\johnsmith\\: ");
    gets(path);
    printf("Enter the name of the file (eg:MyText.txt): ");
    gets(fname);

    sprintf(complete,"%s%s",path,fname); //this works exactly like printf, except the output is sent to the 'complete' variable.

    fp=fopen(complete,"r");
    if(fp==NULL)
    {
        printf("Cannot open file. Sorry :(");
        getch();
        exit(0);
    }

    while(ch!=EOF)
    {
        ch=fgetc(fp);
        printf("%c",ch);
    }
    fclose(fp);

    return 0;
}


Sprintf is important to me because I need it to run user defined commands in the DOS command line. Eg:
If I want to delete a file the user names, I prompt for the file and get its name:

printf("Enter filename: ");
gets(filename); //assume the user enters 'MyFile.exe'

sprintf(command,"delete %s",filename);

If the user entered 'MyFile.exe', the variable 'command' now contains the string 'delete MyFile.exe'. Now I can delete this file by saying:
system(command);

It comes in really handy sometimes.

No comments:

Post a Comment