在特定路径中打开文件时出现问题 [英] Problem occured when opening file in specific path

查看:78
本文介绍了在特定路径中打开文件时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码从用户提供的路径中打开文件作为输入。



I use this code for opening file from path that user give as input.

string pathOfFile;
//read path of file.
std::cout << "Enter path of file: ";
 
cin >> pathOfFile; 
 
ifstream fp(pathOfFile, ios::in);
 
//check validatly of file and path of file
if (!fp)
{
	cerr << "something wrong while opening file!" << endl;	
	exit(1);
}





我的程序在:D:\ My编程代码\编程代码c ++ \ 1 -algorithm\Huffman代码。



当我输入类似C:\\\\ someText.txt的路径时,程序正常工作,或者当我输入时D:\我的编程代码\programing code c ++ \1-algorithm\Huffman code\ someText.txt

程序无法打开文件并写出我的错误短语出错了打开文件时!。



我使用visual studio 2013和Vs c ++ 11.



my program is in the : "D:\My programming code\programing code c++\1-algorithm\Huffman code".

program work correctly when I enter path like C:\test\someText.txt or any thing else but when I enter "D:\My programming code\programing code c++\1-algorithm\Huffman code\someText.txt"
program can't open file and write my error phrase "something wrong while opening file!".

I use visual studio 2013 and Vs c++11.

推荐答案

// cin是错误的,而应该使用getline(cin,pathOfFile)。 cin当读取空间停止读取更多字符但getline读取完整路径



//cin is wrong instead should use getline(cin, pathOfFile) . cin when read space halt reading more character but getline read full path

string pathOfFile;
//read path of file.
std::cout << "Enter path of file: ";

//cin is wrong instead should use getline(cin, pathOfFile) 
//cin >> pathOfFile;

 getline(cin, pathOfFile);

ifstream fp(pathOfFile, ios::in);
 
//check validatly of file and path of file
if (!fp)
{
	cerr << "something wrong while opening file!" << endl;	
	exit(1);
}


您需要用双引号括起pathOfFile变量,以便操作系统可以处理路径名中的空格。



例如
You need to surround the pathOfFile variable with double-quotes so that the OS can handle the spaces in the path name.

E.g.
pathOfFile = '\"' + pathOfFile + '\"';




在Windows操作系统中,这个问题是由于目录路径名中的空格引起的。

C:\ test\someText.txt中没有任何空格但是

D:\我的编程代码\programing code c ++ \1-algorithm\Huffman代码有很多空格,比如我和编程之间。





您可以将路径放在双引号中,如解决方案1中建议的那样



目录的短路径[ ^ ]。这个API将为您提供目录的简短路径,它看起来像

D:\ My~1



在linux上我不确定这些API是否可用,所以请谷歌为它。



希望这有帮助!!

In Windows operating system this problem is caused because of spaces in the directory path name.
C:\test\someText.txt does not have any spaces in it but
D:\My programming code\programing code c++\1-algorithm\Huffman code has lot of spaces like between My and programming.


You can either put the path in double quotes like suggested in solution 1
OR
go for the Short path of the directory[^]. This API will get you the short path of the directory which will look like
"D:\My ~1"

On linux i am not sure if such APIs are available so please Google for it.

hope this helps !!


这篇关于在特定路径中打开文件时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆