user5405648
user5405648

Reputation:

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;
}

Upvotes: 0

Views: 109

Answers (1)

HuskyDucky
HuskyDucky

Reputation: 1288

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.

Upvotes: 2

Related Questions