C 读/写文件 - 访问冲突

标签 c visual-studio text-files access-violation

我正在尝试从文件中读取和写入简单的中缀和后缀表达式。当程序到达调用 fgets 的行时,会弹出访问冲突错误。

代码:

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

char inFx[100], postFx[100];

int main() {
        FILE *fp = fopen_s(&fp, "input.txt", "r");
        remove("output.txt");
        FILE *fp2 = fopen_s(&fp2, "output.txt", "a");
        if (fp == 0)
        {
            printf("Could not open file\n");
        }
        else
        {
            int i = 0;

            while (fgets(inFx, sizeof(inFx), fp)) {  //access violation during runtime here
                size_t ln = strlen(inFx);
                int n = expEvaluate(inFx, ln, postFx); //refers to other class 
                if (inFx[ln] == '\n')
                   inFx[ln] = '\0';
                if (fp2 == 0)
                {
                    printf("Could not open file\n");
                }
                else
                {
                    while (*(postFx + i) != 0)
                    {
                        fputc(*(postFx + i++), fp2);
                    }
                    fputc('\n', fp2);
                }
            }
        }

        fclose(fp2);
        fclose(fp);


    return 0;
}

最佳答案

fopen_s() 返回错误代码,而不是文件句柄(分配给第一个参数)。

关于C 读/写文件 - 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35161223/

相关文章:

git - 无法在 Azure DevOps 中恢复

javascript - 输出文件中的换行符

c - 如何通过C接收webhook

c - OS X sigaction 错误地设置 sa_mask

c - 如何将枚举值传递到结构中

c - 链表打印功能不起作用

visual-studio - 输入 lambda 符号的更快方法

python - 在python中设置环境变量来运行程序

python - 如何使复选框/框单击更改文本文件? (使用Python和tkinter库)

Python 字符串比较不匹配从文件中读取的行