在 fprintf 函数中写入正确的路径

Writing the correct path in fprintf function

显然,没有关于我的问题的数据(我试着在这里搜索它,但我读过的线程中有 none 回答了我的疑问)。就是这样:我拼命想弄清楚如何将正确的路径放入 fprintf 函数,并且 none 我的尝试已经成功。这是程序:

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

int main(){
FILE *fp = NULL;

//opening the file
fp = fopen("C:/Users/User1/Desktop/myfile.txt", "w+");

//if there's an error when opening the file, the program shuts down
if(fp == NULL){
    printf("error");
    exit(EXIT_FAILURE);
}

//print something on the file the program just opened (or created if not already existent)
fprintf(fp, "to C or not to C, that is the question");

//closing the file
fclose(fp);

//end of main function
return 0;
}

我的问题是:为什么我的程序总是关闭?我究竟做错了什么?这只是一个 Windows 问题(我看到,在 User1 文件夹图标上,有一个锁,可能是权限被拒绝的事情?)或者我只是以错误的方式放置了路径?我尝试使用字符串来保存路径,我尝试更改打开模式,我什至尝试禁用我在计算机上安装的所有防病毒软件、反恶意软件和防火墙,但什么都没有,程序仍然没有创建文件所在的位置我想要。

P.S。抱歉英语不好。 P.P.S。对不起,如果已经发布了类似的问题,我没能找到它。

fp = fopen("C:\Users\User1\Desktop\myfile.txt", "w+");

字符\是C中的转义字符,必须转义:

fp = fopen("C:\Users\User1\Desktop\myfile.txt", "w+");

更好的是,windows 现在支持 / 目录分隔符。所以你可以这样写:

fp = fopen("C:/Users/User1/Desktop/myfile.txt", "w+");

无需转义路径

参考:

MSDN fopen,特别是 Remaks 部分

使用 perror() 让操作系统帮助您确定失败的原因。

#define FILENAME "C:/Users/User1/Desktop/myfile.txt"

    fp = fopen(FILENAME, "w+");

    // report and shut down on error
    if (fp == NULL) {
        perror(FILENAME);
        exit(EXIT_FAILURE);
    }