C, Win32 API: l need help with ReadFile function

Hello,
Happy New Month to you all.

However, l am playing with Createfile, WriteFile and ReadFile functions, Createfile and Writefile works well but my problem is ReadFile.

l want to read the data written to a buffer "szBuffer", by using "ReadFile" to read the data in the szBuffer into another buffer szBuf. But it doesn't work.

When l check the return value like error=ReadFile(hfile,szBuffer,10,&in,NULL), it returns 0 but when l use GetLastError() to check for the return value, it gives me 998. l learnt that the second parameter to ReadFile() is the address to store the data read.
Code snippet below:

1
2
3
4
5
6
7
8
9
10
11
hfile=CreateFile("C:\file.txt",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);// this works well
				
				WriteFile(hfile,szBuffer,256,&in,NULL);//this works well
				
				
				ReadFile(hfile,szBuf,256,&in,NULL);//this does not read data
				CloseHandle(hfile);
					
					hdc=GetDC(hwnd);
					TextOut(hdc,50,300,szerror,wsprintf(szerror,"%i",GetLastError()));//check return value
					ReleaseDC(hwnd,hdc);




Can someone help me to overcome this?

Thanks.
Last edited on
You can lookup what the error means here.
https://msdn.microsoft.com/en-us/library/cc231199.aspx

What does the declaration of those variables look like? We can't give an answer without seeing them.

Your file should be "C:\\file.txt", you have to escape the \.

Where is the file position before the read? It's at the end of the file, right?
Last edited on
As kbw intimated, the file pointer is likely at the end of the file due to the write operation. Possibly could use SetFilePointer() to set to beginning of file.
Ok. l have done necessary corrections but the problem still persists.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static TCHAR szBuffer[100]="Read file testing"; static TCHAR  *szBuf; DWORD in; static TCHAR szerror[100];



hfile=CreateFile("C:\\file.txt",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);// this works well
				
				WriteFile(hfile,szBuffer,10,&in,NULL);//this works well
				
				SetFilePointer(hfile,0,0,FILE_BEGIN);
				ReadFile(hfile,szBuf,10,&in,NULL);//this does not read data
				CloseHandle(hfile);
					
					hdc=GetDC(hwnd);
TextOut(hdc,0,100,szBuf,10)// to see print out, but nothing prints.
					TextOut(hdc,50,300,szerror,wsprintf(szerror,"%i",GetLastError()));//check return value
					ReleaseDC(hwnd,hdc);



When l check for ReadFile return value directly, it gives me 0 but when l check with GetLastError, it gives me 998.

l need directions please.
Last edited on
Is all the code shown above within a WM_PAINT handler?
@Freddie1: No. But l have gotten the answer being that the szbuf was not initialized.
So l set it static TCHAR szBuf[100]={0};

and now it's working well.

Thanks alot for your concern. God bless you all.
Topic archived. No new replies allowed.