Visual Studio C++ 如何正确使用 fopen() 打开 txt 文件

如何解决Visual Studio C++ 如何正确使用 fopen() 打开 txt 文件

我正在学习 C++,练习涉及打开一个 .txt 文件并从中读取。 项目结构如下:

enter image description here

int main()
{

    static const char* full_name = "C:\Users\Lukas\Desktop\Programming\file_system_test\file_system_test\items.txt";
    FILE* my_file = fopen(full_name,"r");
    if (my_file == NULL) {
        perror("error opening file");
    }

}

我正在尝试打开 items.txt 但还没有运气..

enter image description here

因为我提供了完整路径,所以我不确定是什么问题..

迄今为止尝试过的方法

  1. 在完整路径中使用双反斜杠
static const char* full_name = "C:\\Users\\Lukas\Desktop\\Programming\\file_system_test\\file_system_test\\items.txt";

错误仍然存​​在: error opening file: No such file or directory

解决

似乎可以修复此代码的唯一方法是使用原始字符串文字,如下所示:

static const char* full_name3 = R"(C:/Users/Lukas/Desktop/Programming/file_system_test/file_system_test/items.txt)";
    FILE* my_file3 = fopen(full_name3,"r");
    if (my_file3 == NULL) {
        perror("error opening file");
    }

不再返回任何错误

解决方法

注意 escape sequences 的字符串文字,所以你的路径:

static const char* full_name = "C:\Users\Lukas\Desktop\Programming\file_system_test\file_system_test\items.txt";    

包含 \f 转义序列,它被解释为 form feed - new page byte 0x0c in ASCII encoding。此字符不能是路径的一部分,因此会报告 Invalid argument 错误。

还有 compilers complain 其他转义序列是未知的。

有三种方法可以修复它。

  1. 如使用反斜杠转义序列 Luka Rahne 所建议的 \\
  2. 或者通过使用正斜杠(因为 C 假设是可移植的,标准库能够将 Unix 路径分隔符转换为平台特定的路径分隔符)。
static const char* full_name = "C:/Users/Lukas/Desktop/Programming/file_system_test/file_system_test/items.txt";
  1. 如果您使用的是 C++11 或更新版本(您的代码是 C 而非 C++,但标记为 C++),您可以利用原始字符串字面量:
static const char* full_name = R"(C:\Users\Lukas\Desktop\Programming\file_system_test\file_system_test\items.txt)";

在这里,我使用 msvc 进行了一些实时测试(文件名为:open.c):

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

int main(int argc,const char argv[])
{
#if VERSION == 0
    // here '\f' is used to reproduce error "invalid argument":
    static const char name[] = "C:\fUsers\\User\\Downloads\\open.c";
#elif VERSION == 1
    static const char name[] = "C:\\Users\\User\\Downloads\\open.c";
#elif VERSION == 2
    static const char name[] = "C:/Users/User/Downloads/open.c";
#elif VERSION == 3
    static const char name[] = R"(C:\Users\User\Downloads\open.c)";
#endif
    FILE* f = fopen(name,"r");
    
    if (!f) {
        perror("fopen");
        return 1;
    }
    
    char buf[256] = "";
    
    fgets(buf,sizeof(buf),f);
    printf("%s\n",buf);
    
    fclose(f);
    
    return 0;
}

这是从 cmd.exe 编译和运行的结果:

C:\Users\User\Downloads>cl open.c /D VERSION=0 && open.exe
Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29336 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

open.c
Microsoft (R) Incremental Linker Version 14.28.29336.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:open.exe
open.obj
fopen: Invalid argument

C:\Users\User\Downloads>cl open.c /D VERSION=1 && open.exe
Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29336 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

open.c
Microsoft (R) Incremental Linker Version 14.28.29336.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:open.exe
open.obj
#include <stdlib.h>


C:\Users\User\Downloads>cl open.c /D VERSION=2 && open.exe
Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29336 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

open.c
Microsoft (R) Incremental Linker Version 14.28.29336.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:open.exe
open.obj
#include <stdlib.h>


C:\Users\User\Downloads>cl open.c /D VERSION=3 && open.exe
Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29336 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

open.c
open.c(11): warning C4129: 'm': unrecognized character escape sequence
open.c(11): warning C4129: 'D': unrecognized character escape sequence
open.c(11): warning C4129: 'o': unrecognized character escape sequence
open.c(11): error C2065: 'R': undeclared identifier
open.c(11): error C2143: syntax error: missing ';' before 'string'
open.c(11): error C2099: initializer is not a constant

所以一切都如我所描述的那样工作,最后一个版本 3 失败,因为我将代码编译为 C

,

我相信您的问题是文件名中的 \ 未正确转义。 您的文件名字符串应包含双反斜杠字符。

static const char* full_name = "C:\\Users\\Lukas\\Desktop\\Programming\\file_system_test\\file_system_test\\items.txt";

您可以测试这一点,方法是通过 std::cout 发送此字符串进行调试。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?