JC_808
JC_808

Reputation: 15

Modifying user-input file path to scan files in the same directory in C

I'm working on a program where the user inputs the file path, then an additional string with the file name is concatenated to that. I will be using this for multiple files in the same directory. I am using printf statement is just to see if the operation works, however when the output is displayed the filepath is printed twice, then the filename added at the end. For example

Input filepath is C:\Documents\

the output comes out C:\Documents\C:\Documents\HR_1.txt

How can this be corrected?

The relevant code is below

int main()
{
            char folder[50]="";
            printf("Please type file location\n");
            printf("An example of file location is C:\\Documents\\projects\\[Folder]\\");
            printf("\n");
            scanf("%s",folder);
            printf(folder);

            /*Clearing Heart rate file names, opening file*/
            FILE*HR1=NULL;
            printf(strcat(folder,"HR_1.txt"));
    }
}

Upvotes: 0

Views: 721

Answers (1)

dbush
dbush

Reputation: 223852

You have the output of two calls to printf mashed together.

The first parameter to printf should always be a string literal, not a variable. That prevents unintended escape sequences from being interpreted and allows you to put newlines in your formatting.

Because your two calls to printf, one before appending and one after, don't include a newline, they appear on the same line.

So change this:

        printf(folder);
        ...
        printf(strcat(folder,"HR_1.txt"));

To:

        printf("%s\n", folder);
        ...
        printf("%s\n", strcat(folder,"HR_1.txt"));

Output:

C:\Documents\
C:\Documents\HR_1.txt

Upvotes: 1

Related Questions