我正在将一个Unix C应用程序移植到Windows。该应用程序在文件打开时重命名文件,在Unix上完全没有问题,但显然在Windows上无法正常工作。追踪所有的重命名操作,确保我关闭文件,然后重新打开和定位会很痛苦。
考虑到Windows资源管理器允许在使用中重命名文件,我想知道为什么我无法使这个功能正常工作。我已尝试使用C中的rename和MoveFile,以及C#中的System.IO.File.Move。在所有情况下都会失败,并显示“权限被拒绝”的错误(具体而言,由GetLastError()返回的错误是“The process cannot access the file because it is being used by another process”)
任何提示?
我还尝试使用_sopen以共享模式打开文件,但也没有成功(同样的错误)。
感谢Stefan提供的工作中的C#代码:
string orig_filename = "testrenamesharp-123456";
string dest_filename = "fancynewname.txt";
Byte[] info = new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");
var fs = new FileStream(orig_filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
fs.Write(info, 0, info.Length);
File.Move(orig_filename, dest_filename);
fs.Close();
以下是一份可用的C语言示例:
const char* filename = "testrename-XXXXXX";
const char* dest_filename = "fancynewname.txt";
/* The normal POSIX C functions lock the file */
/* int fd = open(filename, O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE); */ /* Fails */
/* int fd = _sopen(filename, O_RDWR | O_CREAT, _SH_DENYNO, _S_IREAD | _S_IWRITE); */ /* Also fails */
/* We need to use WINAPI + _open_osfhandle to be able to use
file descriptors (instead of WINAPI handles) */
HANDLE hFile = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL );
if( INVALID_HANDLE_VALUE == hFile) {
ErrorExit(TEXT("CreateFile"));
}
int fd = _open_osfhandle((long int)hFile, _O_CREAT | _O_RDWR | _O_TEMPORARY);
if( -1 == fd ) {
perror("open");
}
int resw = write(fd, buf, strlen(buf));
if(-1 == resw) {
perror("write");
}
if( 0 == access(dest_filename, F_OK)) {
perror("access");
}
/* Now try to rename it - On Windows, this fails */
int resr = rename(filename, dest_filename);
if( -1 == resr) {
perror("rename");
}
int resc = close(fd);
if( -1 == resc ) {
perror("close");
}