使用fopen打开文件,在Windows上给定绝对路径

Open file with fopen, given absolute path on Windows

本文关键字:路径 Windows fopen 文件 使用      更新时间:2023-10-16

我正在尝试制作一个计算文件行数的程序,当我试图将绝对路径传递给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"

它不起作用,因为编译器将检查文字字符串中的反斜杠和下一个字符,并通常将它们解释为一个字符。字符串文字中的这两个字符序列称为转义序列

序列Dj不映射到任何东西(与映射到换行符的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)到调试