slavko
slavko

Reputation: 103

File path as user input in C

I couldnt find specific answer to my question. I am really low level, just started and had a class in which I learned to create file from the CodeBlocks. Took code with me home but it wont work because its not on the same computer. So, the idea was to make something that will allow user to choose path for the newly formed .txt file. When, instead of s, I manually insert "c:\example.txt" or something like that, the code creates a file "example.txt" but when I send it as input it simply wont. Why?

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

int main()
{
    FILE *a=NULL;
    char s[50];
    puts("Enter the path of the file: ");
    fgets(s,50,stdin);
    a=fopen(s,"w");
    if(a==NULL)
        exit(1);
    else
        printf("Successful input");
}

Upvotes: 3

Views: 4445

Answers (1)

Armali
Armali

Reputation: 19375

So the entire problem was the fgets function which adds the \nat the end? Is there any other idea to make this work?

You can replace the

    fgets(s,50,stdin);

with

    scanf("%49[^\n]%*c", s);

- this reads input excluding the \n into s, as long as its size allows, and consumes the \n, so that it doesn't get into the way of possible later input.

Upvotes: 2

Related Questions