C程序未写入文件吗?

问题描述 投票:0回答:2

收到输入后,我的程序将不会写入文件。其他一切似乎都按预期进行。

我哪里出错了?

我正在尝试使用的输入是“测试”,没有引号。

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

int main() {
    char fileSelectionInput[20];

    printf("Select a file to print to: ");
    scanf("%s", &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, "a+");

    if (testFile == NULL) {
        puts("Opps?");
        return 0;
    }

    int writesLeft = 10;

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

    fclose(testFile);

    return 0;
}
c stdio
2个回答
0
投票

问题基本上是使用gets。

尝试以下更改,在我使用scanf和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) {
       puts("Found some issue when I tried to open the file");
       return 1;
    }

    int writesLeft = 10;

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

    fclose(testFile);

    return 0;
}

-1
投票

您应使用a+将文本附加到文件,w+会更改文件的文本。

© www.soinside.com 2019 - 2024. All rights reserved.