I’m trying to use the createFile
and it says it can’t open it (Could not open file (error 2)). I tried to make the fileName the name of the file and the path to it. The file is just a text file with some words in it. I tried to “Verify File Access”, “Testing with a Simplified Path (LPCSTR fileName = "example.txt"
)”, “Check File Path Syntax (LPCSTR fileName = "C:\Users\YourUsername\Desktop\example.txt"
)”, “Confirm File Location”, “Confirm Working Directory”.
The code I’m using is
#include <windows.h>
#include <stdio.h>
int main() {
// Specify the absolute path to the file
LPCSTR fileName = "C:\Users\97250\OneDrive\שולחן העבודה\example.txt";
// Attempt to open the file
HANDLE fileHandle = CreateFileA(
fileName, // File name
GENERIC_READ, // Desired access
0, // Share mode
NULL, // Security attributes
OPEN_EXISTING, // Creation disposition
FILE_ATTRIBUTE_NORMAL, // Flags and attributes
NULL // Template file handle
);
if (fileHandle == INVALID_HANDLE_VALUE) {
printf("Could not open file (error %d)n", GetLastError());
return 1;
}
// Buffer to store the data read
char buffer[1024];
DWORD bytesRead;
// Read data from the file
BOOL readResult = ReadFile(
fileHandle, // File handle
buffer, // Buffer to store data
sizeof(buffer) - 1, // Number of bytes to read
&bytesRead, // Number of bytes read
NULL // Overlapped
);
if (!readResult) {
printf("Could not read from file (error %d)n", GetLastError());
CloseHandle(fileHandle);
return 1;
}
// Null-terminate the buffer to make it a valid string
buffer[bytesRead] = '';
// Print the contents of the buffer
printf("File contents:n%sn", buffer);
// Close the file handle
CloseHandle(fileHandle);
return 0;
}
1