You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C语言程序无法写入文件?仅生成空文件问题求助

Why Your Code Isn't Writing to the File

Let's walk through the key issues stopping your program from writing data to rooms.txt:

1. Incorrect scanf Arguments (The Main Culprit)

When using scanf to read into integer variables, you must pass the memory address of the variable, not the variable itself. Your code is passing rm.room, rm.cap, and rm.price directly—this tells scanf to write input values to invalid memory locations, which usually causes the program to crash before it even reaches the fprintf step, or reads garbage values that don't get written properly.

Fix this by adding the & (address-of operator) to your integer scanf calls:

scanf("%d", &rm.room);   // Correct: pass address of rm.room
scanf("%d", &rm.cap);    // Correct
scanf("%d", &rm.price);  // Correct

Note that rm.type is a character array—its name already acts as a pointer to the first element, so you don't need & there (that part was right!).

2. No Check for File Open Failure

You're calling fopen but not verifying if it succeeded. If the file can't be created (e.g., due to permission issues, invalid path), fopen returns NULL. Writing to a NULL file pointer with fprintf leads to undefined behavior, and your program won't write anything at all.

Add a quick check to handle this scenario:

FILE *k = fopen("rooms.txt","w");
if (k == NULL) {
    perror("Failed to open file"); // Prints a human-readable error message
    exit(EXIT_FAILURE);
}

3. Redundant Global Variables (Not Critical, But Bad Practice)

You've defined struct room rm and FILE *k globally, then redefined struct room rm inside main(). The local rm overrides the global one, which doesn't break the code directly but can cause confusion later. It's better to declare variables only where they're needed (like inside main()).


Fixed Full Code

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

struct room {
    int room;
    char type[9];
    int cap;
    int price;
};

int main(){
    struct room rm;
    FILE *k = fopen("rooms.txt","w");
    
    if (k == NULL) {
        perror("Could not open rooms.txt");
        return EXIT_FAILURE;
    }

    printf("Please enter room number:");
    scanf("%d", &rm.room);
    printf("\nPlease enter a description:");
    scanf("%s", rm.type);
    printf("\nPlease enter the room capacity:");
    scanf("%d", &rm.cap);
    printf("\nPlease enter the price:");
    scanf("%d", &rm.price);

    fprintf(k,"%d\t %s\t %d\t %d\n", rm.room, rm.type, rm.cap, rm.price);
    fclose(k);
    
    return 0;
}

Run this corrected version, and it should properly read your input and write it to rooms.txt.

内容的提问来源于stack exchange,提问作者Saltwalker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:35:13