迷途的启木菌 2019-11-15 14:38 采纳率: 50%
浏览 274
已采纳

文件操作,fopen的疑问,以及无法编辑文件,请大佬指教,谢谢!

开始接触文件类很迷惑,按着书本敲的

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    FILE *fp;
    char ch;
    if (!(fp=fopen_s("d:\\wenjian\\test.txt", "wt")))
    {
        printf("cannot open file!\n");
        getchar();
        exit(1);
    }
    printf("please put in char:\n");
    while ((ch = getchar()) != '\n')
        fputc(ch, fp);
    fclose(fp);
    getchar();
    return 0;
}

错误信息:
cpp(7): warning C4129: “w”: 不可识别的字符转义序列
error C2660: “fopen_s”: 函数不接受 2 个参数
note: 参见“fopen_s”的声明

第二三个错误信息,虽然可以解决,但是没有弄明白
按照网上的做法将 if (!(fp=fopen_s("d:\wenjian\test.txt", "wt")))改为了 if (!(fopen_s(&fp,"d:\wenjian\test.txt", "wt"))) 这样第二三错误就没有了,但是fopen的定义是FILE* fopen(const char* filename,const char* mode); 是我的书老版了吗。

替换后

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    FILE *fp;
    char ch;
    if ((fopen_s(&fp ,"d:\\wenjian\\test.txt", "wt"))==NULL)
    {
        printf("cannot open file!\n");
        getchar();
        exit(1);
    }
    printf("please put in char:\n");
    while ((ch = getchar()) != '\n')
        fputc(ch, fp);
    fclose(fp);
    getchar();
    return 0;
}

可以创建文件,但是无法打开写入数据,直接就cannot open file!退出了,请问我的问题出在那里啊,我是按着书上敲的

  • 写回答

4条回答 默认 最新

  • 文文爹 2019-11-15 15:11
    关注

    if ((fopen_s(&fp ,"d:\wenjian\test.txt", "wt"))==NULL)

    有问题:当打开成功,返回值是NULL

    应改为 if ((fopen_s(&fp ,"d:\\wenjian\\test.txt", "wt"))!=NULL)  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题