怎样用createfile和readfile打开和读取硬盘上已经存在的文件?
1. 我用createfile打开已存在文件时,第一个参数文件名应该写成什么样格式?很多网友写的似乎是 "c:\\test.txt",但我写成这个样子程序运行时就找不到文件,写成"c: \\
test.txt",这样就可以成功打开文件。请问这是怎么回事?(注意我的写法中在 c: 后面多了一个空格)
2.我如上打开文件后,用readfile读取文件,函数返回值为true,表明读取成功,但返回的已读取字节数却总是零。查msdn,只有文件指针已经指到文件尾时才会发生这种事,但我的文件是刚刚打开的啊。且该文件确实存在,非空,可以用记事本打开。我试图在读取前用setfilepointer强行把文件指针指到文件头再读取,但依旧发生这种错误。
我的程序代码如下:
#include "stdafx.h"
#include <windows.h>
#include <iostream.h>
int main(int argc, char* argv[])
{
HANDLE fileHandle;
char s[ 10];
BOOL success;
DWORD numRead;
fileHandle=CreateFile(
"C: \\test.txt",GENERIC_READ,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(fileHandle==INVALID_HANDLE_VALUE)
{
cout<< "error number " << GetLastError()
<< " occured on file open." << endl;
return 0;
}
//success=SetFilePointer(fileHandle,1,0,FILE_BEGIN);
success=ReadFile(fileHandle,s,1,&numRead,0);
cout << success << endl;
cout << numRead;
return 0;
}
请各位多指点,谢谢!