gpt4 book ai didi

c++ - 为什么 std::fopen 和 std::filebuf::open 在 Windows 上修剪尾随空格字符?

转载 作者:行者123 更新时间:2023-11-30 02:07:38 24 4
gpt4 key购买 nike

在尝试将一段 C++ 代码从 MSWindows 移植到 Linux (Mint10) 时,我偶然发现了一个奇怪的问题。我发现硬编码文件名中有一个小错字:尾随空格字符 (\x20)。

该代码在 Windows (Windows Vista/7) 下工作得很好,但在 linux 下处理错误文件名时遇到了麻烦。我发现 std::filebuf::openstd::fopen(还有 boost::filesystem::filebuf)都允许尾随Windows 下文件名中的空格字符(我认为这是不正确的行为)。

我在 Win7 下使用 MSVC2010 和 MinGW 测试了以下代码:

# include <iostream>
# include <fstream>
# include <string>
# include <cstdlib>

const std::string filename = "Z:\\Path\\To\\A\\File " ; // one trailing space

int main(int, char * [])
{
std::cout << "Testing with file : \"" << filename << "\"" << std::endl ;

// Testing with std::filebuf::open
std::filebuf fb ;
fb.open(filename.c_str(), std::ios::in | std::ios::binary) ;
if( fb.is_open() )
{
std::cout << "Using std::filebuf : Opened" << std::endl ;
fb.close() ;
}
else
{
std::cout << "Using std::filebuf : Not opened" << std::endl ;
}

// Testing with std::fopen
std::FILE * fp = std::fopen(filename.c_str(), "rb") ;
if( fp )
{
std::cout << "Using std::fopen : Opened" << std::endl ;
std::fclose(fp) ;
}
else
{
std::cout << "Using std::fopen : Not opened" << std::endl ;
}
return 0 ;
}

我确认硬盘驱动器上的文件名称中没有尾随空格字符。该文件已在 Windows 上成功打开,但如果文件名不完全匹配,则无法在 linux 下访问它。

所以我有几个问题:

  • 这是 Windows 下文件 API 的正常行为吗?还有其他陷阱吗?我用谷歌搜索但没有找到关于这个案例的引用。 (也许我是一个糟糕的 googler :))
  • 如何编写以严格方式使用文件名的代码?在将文件名传递给某些文件函数之前总是修剪文件名并不是我的解决方案;我当前的应用程序必须列出目录(使用 boost::filesystem::directory_iterator),如果用户提供的文件名带有尾随空格字符(这种情况很少见,但在许多文件系统上允许),修剪文件名将破坏应用程序).

谢谢你的建议!

最佳答案

Windows 本身会从文件名中去除尾随空格,这与您用来打开文件的 C++ 函数无关。

这是 Windows API 函数 CreateFile 中对此行为的一个引用:INFO: Filenames Ending with Space or Period Not Supported

关于c++ - 为什么 std::fopen 和 std::filebuf::open 在 Windows 上修剪尾随空格字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7603420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com