How to properly create and write to file?

Hi I am currently trying to create a file and write some content into it :P

However I believe that either the something with the path is wrong or I am doing the creation of the file wrong (maybe some attributes wrong?), anyway here's the source:
1
2
3
4
5
6
CreateFile(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL) //path is something like ".\\folder\\email@host.com\\file.txt"
char* buffer = "some long content";
		
FILE* newFile = fopen(path, "w+");
fwrite(buffer, size, 1, newFile);
fclose(newFile);


he successfully creates the empty file with the Windows API Function, however he then crashes at fwrite with
1
2
3
4
5
6
7
8
"Debug Assertion Failed!
...
File: ...\src\frwrite.c
Line: 77

Expression: (stream != NULL)

...Press Retry to debug... 
someone know what could be the problem?
Last edited on
The fopen call returns NULL in your case.
Why are you mix winapi functions with CRT functions ? Use WriteFile instead.
Well in order to use WriteFile I need a handle which I can only get by using FILE* newFile = fopen(path, "w+"); or did I misunderstand something here?

Also I used it before instead of fwrite() and fclose() but it also didnt work (and I dont know how to read the error that GetLastError() returns).


edit: I simply made a DWORD where I saved the return value in so I could read it out. what I got was 6 so I assume the corresponding error code is 0x6 which would be ERROR_INVALID_HANDLE, just as I supected.

maybe you could explain why fopen returns NULL? thanks

edit: I managed to kind of solve the problem (by rewriting some code and using different functions).
Last edited on
Topic archived. No new replies allowed.