#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
/* Maximum size plus one */
#define MAX_BUF_SZ 101
int main(void){
char readBuffer[MAX_BUF_SZ];
DWORD bytesRead;
char buffer[MAX_BUF_SZ] = "Test string";
DWORD bytesWritten;
HANDLE fh = CreateFile(("newfile.txt"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(fh!=INVALID_HANDLE_VALUE){
printf("File opened for reading!\n");
} else {
printf("File not opened for reading!\n");
exit(EXIT_FAILURE);
}
if (WriteFile(
fh, // takes a file handle
buffer, // a buffer
strlen(buffer), // length of buffer
&bytesWritten, // pointer where you want to store the number of bytes written to the file
NULL // OVERLAPPED struct, setting to NULL
))
{
printf("File written to.\n");
}else{
printf("File not written to.\n");
}
/* Retrieves the size of the specified file. */
LARGE_INTEGER moveTo;
LARGE_INTEGER size2;
GetFileSizeEx(fh, &moveTo);
moveTo.QuadPart = 11 * -1;
printf("The file size is %lld bytes\n", moveTo.QuadPart);
SetFilePointerEx(fh, moveTo, &size2, FILE_END);
if(ReadFile(fh, readBuffer, sizeof(readBuffer), &bytesRead, NULL)){
printf("File successfully read!\n");
printf("%d bytes read.\n", bytesRead);
//readBuffer[(bytesRead / sizeof(char))] = ' ';
printf(("%s\n"), readBuffer);
}
CloseHandle(fh);
return EXIT_SUCCESS;
}
This is my code. The goal here is to create a file, write a string to that file, then read the contents in that file. I learned that I need to use SetFilePointerEx to reset where the file pointer points to (I want it to point back to the beginning). However, this is my output:
File opened for reading!
File written to.
The file size is -11 bytes
File successfully read!
11 bytes read.
Test string@
I get an extra character and Im not sure why. Am I setting/using up SetFilePointerEx correctly? Do I even need to use SetFilePointerEx