943,998 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 29265
  • C RSS
You are currently viewing page 1 of this multi-page discussion thread
Aug 27th, 2005
0

Windows API functions to read and write files in C

Expand Post »
Hello, I'm playing with win API functions readFile and WriteFile.
Is it possible to open file using CreateFile in binary mode just like using fopen standard C function.
I tried with function WriteFile to write string to a file but it seems that file is opened in textual mode. What I'm trying to do is to open file in binary mode and then to write strings so that cannot be opened and examined with Notepad.

Thank you very much
Similar Threads
Reputation Points: 55
Solved Threads: 6
Junior Poster
Micko is offline Offline
148 posts
since Aug 2005
Aug 27th, 2005
0

Re: Windows API functions to read and write files in C

There's no way to specify the orientation of a file opened by CreateFile, it's always binary. ReadFile and WriteFile work with raw bytes.

>What I'm trying to do is to open file in binary mode and then to write
>strings so that cannot be opened and examined with Notepad.
Printable characters in the character set will always be readable by Notepad, whether you're using binary or text orientation. If you want your strings to be unreadable, you need to encrypt them somehow rather than just write them straight to the file:
  1. #include <windows.h>
  2.  
  3. int main ( void )
  4. {
  5. HANDLE out = CreateFile ( "test.txt", FILE_WRITE_DATA, 0, NULL,
  6. CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
  7. char s[] = "This is a test";
  8. int i, j;
  9. int n;
  10.  
  11. for ( i = 0, j = sizeof s - 1; i <= j; i++, j-- ) {
  12. s[i] ^= s[j] ^ 194837U;
  13. s[j] ^= s[i] ^ 3876U;
  14. }
  15.  
  16. WriteFile ( out, s, sizeof s, &n, NULL );
  17. CloseHandle ( out );
  18.  
  19. return 0;
  20. }
However, you can directly write numbers and other non-string data without the encryption, and it will be unrecognizable when opened with Notepad:
  1. #include <windows.h>
  2.  
  3. int main ( void )
  4. {
  5. HANDLE out = CreateFile ( "test.txt", FILE_WRITE_DATA, 0, NULL,
  6. CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
  7. int i = 12345;
  8. int n;
  9.  
  10. WriteFile ( out, &i, sizeof i, &n, NULL );
  11. CloseHandle ( out );
  12.  
  13. return 0;
  14. }
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Aug 28th, 2005
0

Re: Windows API functions to read and write files in C

Thanks Narue, I understand now

please, can you check if this is a correct way of reading file:
first, file is open for both writing and reading
  1. hFile = CreateFile("MYFILE.TXT", // open MYFILE.TXT
  2. GENERIC_WRITE | GENERIC_READ,
  3. FILE_SHARE_READ, // share for reading
  4. NULL, // no security
  5. OPEN_ALWAYS, // existing file only
  6. FILE_ATTRIBUTE_NORMAL, // normal file
  7. NULL); // no attr
second I want to read contents of a file and display it on screen (I know that file contents are sentences (strings) like
"This is first sentence"
"This is second sentence"
so this is code for reading:

  1. while(ReadFile(hFile, buf, sizeof buf, &dw_bytes_read, NULL) && dw_bytes_read != 0)
  2. {
  3. WriteFile(hStdOut, buf, dw_bytes_read, &dw_bytes_written, NULL);
  4. }

I had one nasty problem, At first I tried this:
  1. while(ReadFile(hFile, buf, sizeof buf, &dw_bytes_read, NULL)){...
but program ended up in an infinite loop (not like fwrite in C) and that way with dw_bytes_read it appears to work fine.
Can you suggest me other, better, way of doing this if this is not OK

Thanks
Reputation Points: 55
Solved Threads: 6
Junior Poster
Micko is offline Offline
148 posts
since Aug 2005
Aug 28th, 2005
0

Re: Windows API functions to read and write files in C

Couldn't you just do something like this? Remeber if this sucks I am not good at the API
  1. #include <windows.h>
  2. #include <iostream>
  3.  
  4. int main()
  5. {
  6. char buf[30] = {'\0'}; //Null terminate
  7. LPVOID lpMsgBuf;
  8. DWORD byteWritten = 0;
  9. HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  10. BOOL ReadFileReturn;
  11.  
  12. HANDLE hFile = CreateFile("MYFILE.TXT", // open MYFILE.TXT
  13. GENERIC_WRITE | GENERIC_READ,
  14. FILE_SHARE_READ, // share for reading
  15. NULL, // no security
  16. OPEN_EXISTING, // existing file only
  17. FILE_ATTRIBUTE_NORMAL, // normal file
  18. NULL); // no attr
  19.  
  20. ReadFileReturn = ReadFile(hFile,buf,30,&byteWritten,NULL);
  21. if(ReadFileReturn)
  22. {
  23. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  24. NULL,
  25. GetLastError(),
  26. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  27. (LPTSTR) &lpMsgBuf,
  28. 0,
  29. NULL);
  30. WriteFile(hStdOut,buf,sizeof buf,NULL,NULL);
  31.  
  32. }
  33. else
  34. {
  35. WriteFile(hStdOut,"It Failed",sizeof "It Failed",NULL,NULL);
  36.  
  37. }
  38. std::cin.get();
  39. return 0;
  40. }
;
Reputation Points: 14
Solved Threads: 4
Junior Poster
prog-bman is offline Offline
108 posts
since Nov 2004
Aug 28th, 2005
0

Re: Windows API functions to read and write files in C

>OPEN_ALWAYS, // existing file only
OPEN_ALWAYS creates the file if it doesn't exist. If you want CreateFile to fail if the file doesn't exist, use OPEN_EXISTING.

>but program ended up in an infinite loop
That's because with the way you open the file, reaching end-of-file still returns success.

>Can you suggest me other, better, way of doing this if this is not OK
Well, there's nothing wrong with it, so it all boils down to style preference.

>Couldn't you just do something like this?
Sure, but where's the loop?
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Aug 28th, 2005
-1

Re: Windows API functions to read and write files in C

Quote originally posted by Micko ...
What I'm trying to do is to open file in binary mode and then to write strings so that cannot be opened and examined with Notepad.
I am not sure if writing strigs in binary mode is a good idea.
Either you will end up writing the memory locations to the file, which would not be useful in the second time around when you open it or you will end up writng human readable stuff any way.

I think what you are looking for is some encrypting mechanism so that you could hide the strings from the others.

----------------------

Programming ( Assignment / Project ) Help
Reputation Points: 10
Solved Threads: 0
Light Poster
proghelper is offline Offline
28 posts
since Jun 2005
Aug 28th, 2005
0

Re: Windows API functions to read and write files in C

>I am not sure if writing strigs in binary mode is a good idea.
Only if you write the file with CreateFile and WriteFile, then read it using a FILE* opened with text orientation. Then it's possible to have conversion issues depending on the contents of the strings. But as long as the file is consistently read and written as binary, there's no problem.

>Either you will end up writing the memory locations to the file
No, you wouldn't. WriteFile takes a pointer and writes the contents of that pointer, so the only way to get WriteFile to write the addresses is if you had an array of pointers representing the strings and passed it like this:
  1. char *lines[N];
  2.  
  3. ...
  4.  
  5. WriteFile ( h, lines, N * sizeof *lines, &n, NULL );
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Aug 28th, 2005
0

Re: Windows API functions to read and write files in C

Thank you all for replies. Usually I do all file manipulation stuff with fopen, fwrite, fread and etc, but I wanted to know how this is done with API. Also I've read somewhere that C function fopen end up on CreateFile (under windows os) and that "would be wise" to use it directly to gain better performance. I don't know if this is true, I doubt it.

Thanks again
Reputation Points: 55
Solved Threads: 6
Junior Poster
Micko is offline Offline
148 posts
since Aug 2005
Aug 28th, 2005
0

Re: Windows API functions to read and write files in C

yes, its true that with M$ compilers fopen and fstream eventually use win32 api functions. But there are a lot of reasons not to use win32 api for reading/writing text files and buffered i/o. Using either fstream or fgets() its really easy to read just one line of text (up to CR/LF), but win32 api its not so easy because you, the programmer, have to duplicate the functionality of fgets().

Bottom line: use win32 api directly only if speed is important to your program. Otherwise use either fstream or FILE and associated functions. Personally, I hate fstream because I think its ugly and very clumbsy. The only advantage is getline() used with std::string object. But for formatted i/o you can't beat the ease of fprintf() and fscanf().
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,953 posts
since Aug 2005
Oct 19th, 2010
0
Re: Windows API functions to read and write files in C
the easiest way is that you save the file with the extension of (.bin) instead of (.txt)
Reputation Points: 10
Solved Threads: 0
Newbie Poster
progneer.soft is offline Offline
7 posts
since Jun 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: A problem about double pointer and double dimension array
Next Thread in C Forum Timeline: hw assignment help on selection & merge sort





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC