如何正确使用 fopen 和 fopen_s,有什么区别?我的代码编译不正确

How do I properly use fopen and fopen_s, and what is the difference? My code is not compiling properly

提问人:stephanp 提问时间:11/7/2023 最后编辑:Weather Vanestephanp 更新时间:11/7/2023 访问量:64

问:

我正在用 C 语言为一个使用文件处理来保存和加载数据的学校项目编写一个基本的座位预订程序。每当我尝试运行该程序时,我都会收到错误,告诉我 fopen 不安全,所以我使用了 _CRT_SECURE_NO_WARNINGS,但它仍然不起作用。我不像其他人那样在编码方面经验丰富,所以这就是我来这里的原因。我希望有人能向我解释如何正确解决这个问题,以免将来发生。

这是我的代码中的问题部分:

// ...

void saveData(SEAT seats[], int seatNum) {
    FILE* file = fopen("seat_config.dat", "wb");
    if (file != NULL) {
        fwrite(seats, sizeof(SEAT), seatNum, file);
        fclose(file);
        printf("\n\nData saved to file: seat_config.dat");
    }
    else {
        fprintf(stderr, "\n\nERROR: Unable to save data to file.\n\n");
    }
}

void loadData(SEAT seats[], int seatNum) {
    FILE* file = fopen("seat_config.dat", "rb");
    if (file != NULL) {
        fread(seats, sizeof(SEAT), seatNum, file);
        fclose(file);
        printf("\n\nData loaded from file: seat_config.dat\n\n");
    }
}
// done

SEAT是一个包含座位 ID 号、占用状态、占用者名字和姓氏的结构。

我可能缺少其他部分,但这是 Visual Studio 指示存在问题的地方。

我还在下面包含了我的 library.h 头文件,其中包含我的所有函数:

#pragma once

void initializeSeat(SEAT seats[], int seatNum);
void printmenuchoice();
void emptySeats(SEAT seats[], int seatNum);
void assignSeats(SEAT seats[], int seatNum);
int lastnameCompare(void* a, void* b);
int firstnameCompare(void* a, void* b);
void alphasortSeat(SEAT seats[], int seatNum);
void deleteSeats(SEAT seats[], int seatNum);
void saveData(SEAT seats[], int seatNum);
void loadData(SEAT seats[], int seatNum);
C 文件处理

评论

1赞 Harith 11/7/2023
请参见:stackoverflow.com/q/28691612/20017547
1赞 Retired Ninja 11/7/2023
#define _CRT_SECURE_NO_WARNINGS必须位于 any includes 之前,理想情况下是包含任何内容的任何文件的第一行。您也可以在项目中定义它,以避免将其洒在任何地方。
1赞 Weather Vane 11/7/2023
我把其中的四个放在最上面:、。前三个使 MSVC 关于“弃用功能”的虚假声明保持沉默。#define _CRT_SECURE_NO_WARNINGS#define _CRT_SECURE_NO_DEPRECATE#define _CRT_NONSTDC_NO_DEPRECATE#define _USE_MATH_DEFINES
5赞 Weather Vane 11/7/2023
您的代码是否有效,并且您正在询问警告?功能在即将到来的 C23 标准中仍然有效。通过屈服于Microsoft的需求,您将牺牲代码的可移植性。他们想把你和他们的产品联系在一起。fopen()
1赞 Weather Vane 11/7/2023
您展示了代码的一部分,以及与问题无关的内容。请发布一个最小可重现示例,这是显示您使用的最短完整代码,该代码会产生编译器警告。大约十几行应该可以做到。fopen()

答: 暂无答案