【问题标题】:Does't work fopen_s(&file, "filename", mode) in visual studio 2019 C_language在 Visual Studio 2019 C_language 中不起作用 fopen_s(&file, "filename", mode)
【发布时间】:2021-06-19 09:53:56
【问题描述】:

所以这是我在这里的第一个问题。如果你能帮助我,那将不胜感激。这段代码是关于我的论文的。我正在尝试写入文件并且它可以工作,但尝试读取另一个文件没有读取。我不能让它工作。屏幕上出现“文件未打开”。请帮助我,以读取文件。

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

int main()
{
    FILE* myfile;
    errno_t errorcode = fopen_s(&myfile, "output.txt", "w");

    if (myfile == NULL)
    {
       printf("Error");
    }

    FILE* data; 
    errno_t err = fopen_s(&data, "C:\SA\input.txt", "r");

    //errno_t err = fopen_s(&data, "input.txt", "r");

    if(data==NULL)
    {
       printf("file does not open");
    }
return 0;
getchar();
}

【问题讨论】:

  • if(data==NULL); 你有一个额外的; 这里。投票结束是错字。
  • 1) 你的直接问题是无关的;: if(data==NULL); 2) 如果“打开”失败,你想知道WHY。两种方法:打印errno(或errno_t,就像你在上面的一个地方所做的那样),或者调用perror() 3) ` is a ["metacharacter"](https://en.wikipedia.org/wiki/Metacharacter): you need to "escape" it with another backslash: "C:\\SA\\input.txt"`
  • 您需要转义文件名中的反斜杠 "C:\\SA\\input.txt"
  • 在 C 中,'\' 是转义序列的开始。要获取实际的 '\' 字符,请连续使用两个 "C:\\SA\\input.txt"
  • 以上; cmets 都解释了问题的根源,但没有解释为什么这样做:基本上,; 使您的if 毫无意义,并使您的程序无论如何都执行下一条语句.基本上它会显示“文件未打开”,即使它实际上已经打开了文件

标签: c++ c visual-studio visual-studio-2019


【解决方案1】:

发布的原始代码有两个主要问题:

  • "C:\SA\input.txt" 应该是 "C:\\SA\\input.txt" 或只是 "C:/SA/input.txt"。 Microsoft 的遗留系统使用\ 作为路径分隔符,在C 字符串中必须将其转义为\\(在许多其他语言中也是如此)。 POSIX 系统上的传统路径分隔符是/,Windows 也支持它。
  • if(data==NULL); 是一个空语句的测试,因此没有任何反应。
  • 请注意,您不应在 C 程序中使用 C++ 标头,例如 &lt;iostream&gt;

这是一个简化版:

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

int main() {
    FILE *myfile;
    errno_t err = fopen_s(&myfile, "output.txt", "w");
    if (err) {
        fprintf(stderr, "Cannot open file %s: %s\n",
                "output.txt", strerror(err));
        return 1;
    }

    FILE *data; 
    err = fopen_s(&data, "C:\\SA\\input.txt", "r");
    if (err) {
        fprintf(stderr, "Cannot open file %s: %s\n",
                "C:\\SA\\input.txt.txt", strerror(err));
        return 1;
    }
    getchar();  // keep terminal window open
    return 0;
}

【讨论】:

  • @Ece Uyar - 这是一个很好的总结。如果您觉得有帮助,请务必“投票”和/或“接受”。另外:注意 "C++" "C"; chqrlie 使用“C”语法和“C”标头 (.h) 文件。还要注意他的“C”大括号/缩进样式。
猜你喜欢
  • 1970-01-01
  • 2020-06-03
  • 2023-03-06
  • 2021-06-21
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2020-11-24
  • 2023-03-29
相关资源
最近更新 更多