Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <windows.h>
- #define DATA_SIZE 256
- int main(int argc, char **argv)
- {
- HANDLE hTestFile; // File handle
- LPCTSTR lpszPathToFile; // Path to file from argument argv[1]
- LPCTSTR lpszFileString; // String that we will write to file
- BOOL bIOresult; // File input/output result
- DWORD cbIObytes; // Amount of read/wrote bytes
- TCHAR cReadData[DATA_SIZE]; // Memory for read data
- DWORD dwSetPtr; // Value returned by SetFilePointer()
- if(argc < 2)
- {
- printf("Enter a file name and any string for file input/output\n");
- return -1;
- }
- lpszPathToFile = (LPCTSTR)argv[1];
- lpszFileString = (LPCTSTR)argv[2];
- memset(cReadData, 0x0, DATA_SIZE);
- /* Open file from a command line argument */
- hTestFile = CreateFile(lpszPathToFile,
- GENERIC_READ|GENERIC_WRITE,
- 0,
- NULL,
- CREATE_ALWAYS,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
- if(hTestFile == INVALID_HANDLE_VALUE)
- {
- printf("Can't create the file \"%s\", code %d\n", lpszPathToFile, (int)GetLastError());
- return -2;
- }
- printf("File \"%s\" is opened\n\n", lpszPathToFile);
- /* Write any data in the file */
- bIOresult = WriteFile(hTestFile, // file handle
- lpszFileString, // data file
- strlen(lpszFileString), // data file length
- &cbIObytes, // input amount of bytes in fact
- NULL); // file access: structure OVERLAPPED - asynchronous, NULL - synchronous
- if(bIOresult == FALSE)
- {
- printf("Can't write data in file %s, code %d\n", lpszPathToFile, (int)GetLastError());
- return -3;
- }
- printf("Wrote %d bytes successfully\n", (int)cbIObytes);
- printf("\tDATA: %s\n\n", lpszFileString);
- dwSetPtr = SetFilePointer(hTestFile,
- 0,
- NULL,
- FILE_BEGIN);
- if(dwSetPtr == INVALID_SET_FILE_POINTER)
- {
- printf("Can't set pointer on start of the file for reading\n");
- return -4;
- }
- /* Currently we read wrote bytes from file and output it to console */
- bIOresult = ReadFile(hTestFile,
- cReadData,
- DATA_SIZE,
- &cbIObytes,
- NULL);
- if(bIOresult == FALSE)
- {
- printf("Can't read data from file \"%s\", code %d\n", lpszPathToFile, (int)GetLastError());
- return -5;
- }
- printf("Read %d bytes successfully:\n", (int)cbIObytes);
- printf("\tDATA: %s\n\n", cReadData);
- /* Close the opened file */
- if(!CloseHandle(hTestFile))
- {
- printf("Can't close the file \"%s\", code %d\n", lpszPathToFile, (int)GetLastError());
- return -6;
- }
- printf("File \"%s\" is closed\n\n", lpszPathToFile);
- /* Remove the file */
- if(!DeleteFile(lpszPathToFile))
- printf("Can't delete file \"%s\", code %d\n", lpszPathToFile, (int)GetLastError());
- printf("File \"%s\" is successfully removed\n\n", lpszPathToFile);
- return 0;
- }
Add Comment
Please, Sign In to add comment