显示标签为“File”的博文。显示所有博文
显示标签为“File”的博文。显示所有博文

2007年9月20日星期四

C/C++中判断某一文件或目录是否存在

C/C++中判断某一文件或目录是否存在
1.C++很简单的一种办法:
#include <iostream>
#include
<fstream>
using namespace std;
#define FILENAME "stat.dat"
int main()
{
fstream _file;
_file.open(FILENAME,ios::
in);
if(!_file)
{
cout
<<FILENAME<<"没有被创建";
}
else
{
cout
<<FILENAME<<"已经存在";
}
return 0;
}

2.利用 c 语言的库的办法:

函数名: access
功 能: 确定文件的访问权限
用 法: int access(const char *filename, int amode);
以前一直没用过这个函数,今天调试程序发现了这个函数,感觉挺好用,尤其是判断一个文件或文件夹是否存在的时候,用不着再find了,文件的话还可以检测读写权限,文件夹的话则只能判断是否存在,下面摘自MSDN:

int _access( const char *path, int mode );

Return Value

Each of these functions returns 0 if the file has the given mode. The function returns –1 if the named file does not exist or is not accessible in the given mode; in this case, errno is set as follows:

EACCES

Access denied: file’s permission setting does not allow specified access.

ENOENT

Filename or path not found.

Parameters

path

File or directory path

mode

Permission setting

Remarks

When used with files, the _access function determines whether the specified file exists and can be accessed as specified by the value of mode. When used with directories, _access determines only whether the specified directory exists; in Windows NT, all directories have read and write access.

mode Value Checks File For
00 Existence only
02 Write permission
04 Read permission
06 Read and write permission

Example

/* ACCESS.C: This example uses _access to check the
* file named "ACCESS.C" to see if it exists and if
* writing is allowed.
*/

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

void main( void )
{
/* Check for existence */
if( (_access( "ACCESS.C", 0 )) != -1 )
{
printf(
"File ACCESS.C exists " );
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
printf(
"File ACCESS.C has write permission " );
}
}
Output
File ACCESS.C existsFile ACCESS.C has write permission

3.在windows平台下用API函数FindFirstFile(...):

(1)检查文件是否存在:

#define _WIN32_WINNT 0x0400

#include
"windows.h"

int
main(
int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;

printf (
"Target file is %s. ", argv[1]);

hFind
= FindFirstFile(argv[1], &FindFileData);

if (hFind == INVALID_HANDLE_VALUE) {
printf (
"Invalid File Handle. Get Last Error reports %d ", GetLastError ());
}
else {
printf (
"The first file found is %s ", FindFileData.cFileName);
FindClose(hFind);
}

return (0);
}

(2)检查某一目录是否存在:

///目录是否存在的检查:
bool CheckFolderExist(const string &strPath)
{
WIN32_FIND_DATA wfd;
bool rValue = false;
HANDLE hFind
= FindFirstFile(strPath.c_str(), &wfd);
if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
rValue
= true;
}
FindClose(hFind);
return rValue;
}

4.使用boost的filesystem类库的exists函数

#include <boost/filesystem/operations.hpp>
#include
<boost/filesystem/path.hpp>
#include
<boost/filesystem/convenience.hpp>

int GetFilePath(std::string &strFilePath)
{
string strPath;
int nRes = 0;

//指定路径
strPath = "D:\myTest\Test1\Test2";
namespace fs = boost::filesystem;

//路径的可移植
fs::path full_path( fs::initial_path() );
full_path
= fs::system_complete( fs::path(strPath, fs::native ) );
//判断各级子目录是否存在,不存在则需要创建
if ( !fs::exists( full_path ) )
{
// 创建多层子目录
bool bRet = fs::create_directories(full_path);
if (false == bRet)
{
return -1;
}

}
strFilePath
= full_path.native_directory_string();

return 0;
}


利用c++标准库函数实现判断文件存在 CSDN Blog推出文章指数概念,文章指数是对Blog文章综合评分后推算出的,综合评分项分别是该文章的点击量,回复次数,被网摘收录数量,文章长度和文章类型;满分100,每月更新一次。

利用c++标准库函数实现判断文件存在 CSDN Blog推出文章指数概念,文章指数是对Blog文章综合评分后推算出的,综合评分项分别是该文章的点击量,回复次数,被网摘收录数量,文章长度和文章类型;满分100,每月更新一次。
在c++标准库函数中,没有直接判断文件存不存在的函数。而为了这一个小小的功能要实现操作系统代码分开很是划不来。
在偶然的机会中,发现了一个很简单的好方法可以实现这个功能。只利用标准库函数而不用写操作系统相关代码。
在c++标准库中,有一个文件操作函数,rename用于文件改名,其位于cstdio中。rename接受new,old两个char*参数,返回改名操作结果。我们可以利用改名功能,将其两个参数都设置成要判断的文件名,而返回值可能会是我们需要的结果。
rename返回0表示正常,返回非0表示有错误。而这样实现的exist函数,同样,返回0表示存在,非0表示不存在。还可以根据需要,将0所对应结果反过来。
最后的实现就是return !rename(filename, filename)。

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=916628

检测文件存在的四种方法。test if a File exist or not?

检测文件存在的四种方法。test if a File exist or not?

1.
WIN32_FIND_DATA m_data;
HANDLE hFile;

hFile=FindFirstFile(filename,&m_data)

if(hFile==INVALID_HANDLE_VALUE) //file not found

Make sure you close the handle if the file is found.

FindClose(hFile);

2.
You can use SHGetFileInfo()
The prototype of the function is as follows:

DWORD_PTR SHGetFileInfo(
LPCTSTR pszPath,
DWORD dwFileAttributes,
SHFILEINFO *psfi,
UINT cbFileInfo,
UINT uFlags
);


3.
PathFileExists

4. 加一个标准c库函数

Example

/* ACCESS.C: This example uses _access to check the
* file named "ACCESS.C" to see if it exists and if
* writing is allowed.
*/

#include
#include
#include

void main( void )
{
/* Check for existence */
if( (_access( "ACCESS.C", 0 )) != -1 )
{
printf( "File ACCESS.C exists\n" );
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
printf( "File ACCESS.C has write permission\n" );
}
}

2007年9月6日星期四

C、C++ 文件系统操作(改名、删除等)

删除文件我在windows下面用了_unlink()函数,在PPC上也编译通过,我就没当回事情。没想到在Linux的gcc上又编译不通过。。。

今天在网上找了好多次文件删除等操作的方法,始终没看到和我心意,能和平台无关的。最后苍天不负有心人啊,还是让我找到了 :)
look:
int remove ( const char * filename );
int rename ( const char * oldname, const char * newname );
恩,也就这两个了:)

文件复制嘛,可以看我的

如何用c++的流操作复制文件

呵呵,开心好多

不过这里要尤其注意的是,Windows和Linux的分隔符不同!!
Windows: \
Linux: /

我就因此而犯错。。。

呵呵,不能再犯啦!!!

2007年9月4日星期二

如何用c++的流操作复制文件

如何用c++的流操作复制文件
无双
荣誉斑竹
Rank: 14Rank: 14Rank: 14Rank: 14
天才猪



UID 4
精华 84
积分 5866
帖子 11395
活跃指数 0
LU金币 4248 个
LU金条 0 个
阅读权限 200
注册 2003-9-16
来自 杭州
使用C++标准程序库的输入输出流(I/O Stream)复制文件,存在许多的方法,

方法一:逐个字符复制

#include <>


std::ifstream input("in",ios::binary);
std::ofstream output("out",ios::binary);
char ch;


while (input.get(ch)) output << ch;

注意:如果使用input>>ch读取字符,则必须先调用input.unsetf(ios::skipws)取消输入流默认的跳过空白符的输入格式,因为换行符是空白符的一种。

方法二:逐行复制

#include <>
#include <>


std::ifstream input("in",ios::binary);
std::ofstream output("out",ios::binary);
std::string line;


while (getline(input,line)) output << line << "\n";

注意:这里的代码有一个小小的缺陷,如果文件不是纯文本格式的文件,或者文本文件的最后没有换行符,那么会导致复制后的文件末尾添加了一个多余的换行符。

方法三:迭代器复制

#include <>
#include <>
#include <>


std::ifstream input("in",ios::binary);
std::ofstream output("out",ios::binary);
input.unsetf(ios::skipws);


copy(istream_iterator(input),istream_iterator(),ostream_iterator(output,""));

同样这里也有一个小技巧,输入流的格式默认为跳过空白字符,因此调用unsetf取消这个格式,才可保证正确的复制。

方法四:缓冲区复制

#include <>


std::ifstream input("in",ios::binary);
std::ofstream output("out",ios::binary);


output << input.rdbuf();

这里直接使用了输入流的缓冲区,因此没有引入额外的临时对象。

很 显然,上述四种方法中,最后一种方法最简洁,由于直接操作输入流的缓冲区,从运行效率上来说,也比其他方法有着略微的优势(当然,由于操作系统可能提供了 额外的基于设备的文件缓冲机制,也许你无法证实这一点)。因此,除非要对输入内容进行处理,直接复制文件推荐最后一种方法,既不容易出错,又能获得良好的 性能。

How do I get the date a file was last modified?

How do I get the date a file was last modified?

I wanted to be able to use the date that a file was last modified, to set the filename of another file. It took me quite a while to find out how to get hold of the date and it turns out that there are three dates on UNIX/Linux. You can use the stat() function.

 

#include

#include

#include



struct tm* clock; // create a time structure

struct stat attrib; // create a file attribute structure

stat("afile.txt", &attrib); // get the attributes of afile.txt

clock = gmtime(&(attrib.st_mtime)); // Get the last modified time and put it into the time structure



// clock->tm_year returns the year (since 1900)

// clock->tm_mon returns the month (January = 0)

// clock->tm_mday returns the day of the month