0
votes

I'm trying to make a small program that saves some information on a file, taking input from the user for the content and name of the file. For some reason, I am unable to save file_name into FILE *open.

This works when input a string as the file name; open = fopen("filename.txt","w"); but not when I try to input string as a variable. I have looked all over and cannot find an answer anywhere.

I have included stdio.h and string.h

int main (){


    FILE *open;

    char first_name[16],last_name[21];
    char save_name[30],ext[10];
    char file_name[40];
    int a,b;

    printf("This program will take your name and save it in a file.\n");
    printf("Insert your first name:");
    scanf("%s",&first_name);
    printf("Insert your last name:");
    scanf("%s",&last_name);


    do{

        printf("Insert file name with extension:");
        scanf("%[^.].%s", &save_name, &ext);
        //Takes filename lenght, minus the dot
        a = (int)strlen(save_name)-1;
        b = (int)strlen(ext);
        sprintf(file_name,"%s.%s",save_name,ext);

    }while(a>8 || b>3);

//This is where my problem lies...

    open = fopen(file_name,"w");

    if(open==NULL){
        printf("File %s failed to open, shutting down...",file_name);
    }
    else{
        fprintf(open, "%s %s",first_name,last_name);
        printf("\n\nSave successful! File was saved as: %s",file_name);
    }

    fclose(open);
    return 0;
}
1
What does your printf at the end print as file_name? Does it have the correct value? - walnut
First of all, what is the input you give the program? Then what is the output? And if you fail to open the file, what does e.g. printing strerror(errno) report? And is the file you want to open in the correct directory? Also please take some time to read about how to ask good questions, as well as this question checklist. - Some programmer dude
"open" is a syscall and is not a good name for any variable. - ulix
@ulix Only in POSIX systems. But I agree that it's a bad name, but on other grounds (it's not descriptive). - Some programmer dude
@uneven_mark - Tested your diagnostic … it looked deceptively correct until I noticed the newline wasn't being printed elsewhere! - Adrian Mole

1 Answers

0
votes

The problem is that your file_name has a leading newline character in it! The newline is being added by your scanf() call with the "%[^.]" format (but I'm not entirely sure why). It seems that using %s for string input automatically removes this but %[^.] will accept all characters except . (including whitespace). Use this to fix it (skipping the newline):

scanf("\n%[^.].%s", &save_name, &ext);

Comments welcome as to where this newline comes from - it's news to me!

PS: You don't need the - 1 in your calculation of a, as the dot is never read into save_name.