使用fopen打开文件,在Windows上给定绝对路径
Open file with fopen, given absolute path on Windows
我正在尝试制作一个计算文件行数的程序,当我试图将绝对路径传递给fopen函数时,它只是告诉我找不到,下面是我的代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[])
{
int i=0;
char array[100];
char caracteres[100];
FILE *archivo;
archivo = fopen("C:Documents and Settingsjuegos psps.txt","r");
if (archivo == NULL){cout<<"Dont Work";}
while (feof(archivo) == 0)
{
fgets(caracteres,100,archivo);
i++;
}
cout << "Number of lines:" << i ;
return 0;
}
我应该如何传递程序的绝对路径,以便您可以打开文件?
使用双斜线:
"C:\Documents and Settings\juegos psps.txt"
它不起作用,因为编译器将检查文字字符串中的反斜杠和下一个字符,并通常将它们解释为一个字符。字符串文字中的这两个字符序列称为转义序列。
序列D
和j
不映射到任何东西(与映射到换行符的n
形成对比),在这种情况下,标准规定编译器可以根据自己的选择来解释它们。一些编译器选择忽略反斜杠,在您的情况下,这将导致等效的结果:
archivo = fopen("C:Documents and Settingsjuegos psps.txt","r");
(您可以尝试创建一个具有此名称的文件,以测试编译器是否就是这样做的)。
反斜杠的正确转义序列是双反斜杠,因此应该将其写成
archivo = fopen("C:\Documents and Settings\juegos psps.txt","r");
在windows和linux上也能正常工作:/
而不是转义反斜杠\
"C:/dir1/dir2/file.ext"
检查文件名中的空格。斜线被恰当地逃脱了,但空白处却没有。
尝试:
fopen("C:\\Documents and Settings\juegos psps.txt","r")
在代码块文件夹中创建一个新文件夹
在主文件和头文件旁边的项目文件夹中,制作新文件"example1",并将您的文件放入其中"file.txt",然后
string nom_fichier;
nom_fichier = "exemple1/file.txt" ;
fichier = fopen(nom_fichier.c_str(), "r+");
如果所有代码和路径都正确键入,导致fopen不起作用的另一个可能原因可能是您的项目属性->C/C++代码生成->运行库设置为/MD,而不是用于调试构建的/MDd,此设置应与项目配置相对应,XX到Release XX(d)到调试
相关文章:
- Windows 非 ASCII 文件路径
- Windows 和 Linux 之间的相对路径分辨率差异?
- 我应该如何获取配置文件的绝对路径与 Windows .exe一起发布?
- 将带斜杠的 Unix 路径转换为 Windows 路径
- 在 Windows 10 下为 VTK 生成 Makefile 时,Qt mkspecs 的路径错误
- Windows上的libtool需要绝对路径,而我已经给了它绝对路径
- 为什么我不能将 Windows 环境路径与 ofstream 一起使用来编写文本文件?
- 找不到 windows.winmd – 如果指定了路径,错误会乘以
- 在 Windows 上,stat 和 GetFileAttributes 对于包含奇怪字符的路径失败
- 在Windows上设置编译器路径
- 从句柄获取Windows Explorer路径
- 如何正确设置Windows路径以通过CMAKE轻松识别
- C Windows-如何从其PID(错误)获取过程路径
- C 检索可执行文件的图标,用于Windows注册表图标路径
- 在 Windows 中加载共享库时在特定路径中选取 dll
- 在Windows上,何时有必要将附加到目录路径上,以使_stat成功
- libclang:添加编译器系统包含路径(Windows中的Python)
- 正在从Registry_TypeGroup1类获取注册表项路径(Windows事件跟踪)
- FreeType字体路径Windows
- 添加目录路径Windows 8.1