尝试使用 fopen 创建/覆盖文件失败

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

我尝试运行以下程序:

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

int main(){
    FILE *datei = fopen("employees.txt", "w");
    fprintf(datei, "Anna\n");

    fclose(datei);
    return 0;
}

如果我理解正确的话,通常应该在我的 C 文件的同一文件夹中生成 .txt 文件,以防该文件夹中不存在该文件,或者如果存在则覆盖它。但是,无论我运行该程序多少次,都不会生成任何文件,也不会覆盖该文件(如果存在)。

然后我认为我的

*.c
文件保存在云中是问题所在,所以我直接将其保存在我的电脑上 - 结果相同。

我继续插入绝对路径:

FILE *datei = fopen("C:\\Users\\für\\JustCoding", "w");
fprintf(datei, "Anna\n");

同样的结果。

我重新启动了我的电脑(Windows 11 Home)并重复上述步骤;什么也没有。

现在我很确定这与编译错误无关,因为我的终端确实显示程序已执行,所以我目前处于停滞状态。

我该如何解决这个问题?

c fopen file-manipulation
1个回答
4
投票

这段代码是正确的,应该在程序的当前工作目录中创建(或覆盖)一个名为“employees.txt”的文件。

您面临的问题可能与以下因素之一有关:

  • 文件正在创建,但不在您要查找的位置。
  • 打开文件时出现错误,但您未捕获该错误。

为了解决这些可能性,让我们修改您的代码以包含错误检查并打印当前工作目录:

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

int main() {
    char cwd[1024];
    if (_getcwd(cwd, sizeof(cwd)) != NULL) {
        printf("Current working directory: %s\n", cwd);
    } else {
        perror("getcwd() error");
        return 1;
    }

    FILE *datei = fopen("employees.txt", "w");
    if (datei == NULL) {
        perror("Error opening file");
        return 1;
    }

    fprintf(datei, "Anna\n");

    fclose(datei);
    printf("File 'employees.txt' should have been created or overwritten.\n");
    return 0;
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.