简体   繁体   中英

C program not writing to file?

My program won't write to the file after input is received. Everything else seems to work as expected.

Where have I gone wrong?

#include <stdio.h>
#include <unistd.h>

int main()
{
    char fileSelectionInput[20];

    printf("Select a file to print to: ");
    gets(fileSelectionInput);

    if (access(fileSelectionInput, F_OK ) == -1) {
        puts("It seems that this file does not exist, sorry.");
        return 0;
    }

    printf("Okay now you can type text to append\n\n");

    FILE* testFile = fopen(fileSelectionInput, "w+");

    int writesLeft = 10;

    while (writesLeft > 1)
    {
        char textInput[50];
        gets(textInput);
        fputs(textInput, testFile);
        writesLeft--;
    }

    fclose(testFile);

    return 0;
}

The problem is basically the use of gets.

Try this changes bellow where I used scanf and fgets:

#include <stdio.h>
// #include <unistd.h>

int main() {
    char fileSelectionInput[20];

    printf("Select a file to print to: ");
    scanf("%19s", fileSelectionInput);  // %19s checks the size of input

    // if (access(fileSelectionInput, F_OK ) == -1) {
    //     puts("It seems that this file does not exist, sorry.");
    //     return 0;
    // }

    printf("Okay now you can type text to append\n\n");

    FILE* testFile = fopen(fileSelectionInput, "a+");

    if (testFile == NULL) {
       perror("fopen()");
       return 1;
    }

    int writesLeft = 10;

    while (writesLeft > 1) {
        char textInput[50];
        fgets(textInput, sizeof(textInput), stdin);
        fputs(textInput, testFile);
        --writesLeft;
    }

    fclose(testFile);

    return 0;
}

When you check the result of fopen , you don't have to check if the file exists with access . This makes your code more portable.

I used %19s in scanf so it won't write past the bounds of the array; 19 characters and 1 null byte fit into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM