首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

怎么用C修改一个文件夹中的所有文件为只读

2012-02-25 
如何用C修改一个文件夹中的所有文件为只读?如何用C修改一个文件夹中的所有文件为只读?最好是测试通过的,谢

如何用C修改一个文件夹中的所有文件为只读?
如何用C修改一个文件夹中的所有文件为只读?最好是测试通过的,谢谢大佬.

[解决办法]
msdn:

Retrieving and Changing File Attributes
An application can retrieve the file attributes by using the GetFileAttributes or GetFileAttributesEx function. The CreateFile and SetFileAttributes functions can set many of the attributes. However, applications cannot set all attributes.


The code example in this topic uses the CopyFile function to copy all text files (.txt) in the current directory to a new directory of read-only files named \TextRO. Files in the new directory are changed to read only, if necessary.

The application creates the \TextRO directory by using the CreateDirectory function.

The application searches the current directory for all text files by using the FindFirstFile and FindNextFile functions. Each text file is copied to the \TextRO directory. After a file is copied, the GetFileAttributes function determines whether or not a file is read only. If the file is not read only, the application changes directories to \TextRO and converts the copied file to read only by using the SetFileAttributes function.

After all text files in the current directory are copied, the application closes the search handle by using the FindClose function.


#include <windows.h>
#include <stdio.h>

void main()
{
WIN32_FIND_DATA FileData;
HANDLE hSearch;
DWORD dwAttrs;
TCHAR szDirPath[] = TEXT( "c:\\TextRO\\ ");
TCHAR szNewPath[MAX_PATH];

BOOL fFinished = FALSE;

// Create a new directory.

if (!CreateDirectory(szDirPath, NULL))
{
printf( "Could not create new directory.\n ");
return;
}

// Start searching for text files in the current directory.

hSearch = FindFirstFile(TEXT( "*.txt "), &FileData);
if (hSearch == INVALID_HANDLE_VALUE)
{
printf( "No text files found.\n ");
return;
}

// Copy each .TXT file to the new directory
// and change it to read only, if not already.

while (!fFinished)
{
lstrcpy(szNewPath, szDirPath);
lstrcat(szNewPath, FileData.cFileName);
if (CopyFile(FileData.cFileName, szNewPath, FALSE))
{
dwAttrs = GetFileAttributes(FileData.cFileName);
if (dwAttrs==INVALID_FILE_ATTRIBUTES) return;

if (!(dwAttrs & FILE_ATTRIBUTE_READONLY))
{
SetFileAttributes(szNewPath,
dwAttrs | FILE_ATTRIBUTE_READONLY);
}
}
else
{
printf( "Could not copy file.\n ");
return;
}

if (!FindNextFile(hSearch, &FileData))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
{
printf( "Copied all text files.\n ");
fFinished = TRUE;
}
else
{
printf( "Could not find next file.\n ");
return;
}
}
}

// Close the search handle.

FindClose(hSearch);
}

[解决办法]
#define INVALID_HANDLE_VALUE (HANDLE)-1

热点排行