'Access Violation Reading Location in C when reading file
I have a program that reads a file, returned from an OPENFILENAME. It has a large edit control. That is supposed to get the text from the file and let the user save it. I just cannot wrap my head around it. fopen(path, "r+") throws an exception for some odd reason.
Exact error message:
"Exception thrown at 0x00007FF87B5A86E2 (ucrtbased.dll) in Notepad (C).exe: 0xC0000005: Access violation reading location 0x000000000000722B."
Here is the function reading it:
void ReadOpenedFile(char* path, HWND hTextBox)
{
// Warning suppressor because it doesn't build without fopen_s it seems.
#pragma warning (disable: 4996)
FILE* f = fopen(path, 'r+');
SetWindowText(hTextBox, f);
fclose(f);
}
I had gotten it from the documents folder, but I knew because Windows protects it, I tried the music folder. It still didn't work. I tried many different websites. They all said the same approach to open files. I always get the same exception. I had tested the OPENFILENAME was returning the correct file path, and it does.
Any help is appreciated!
Solution 1:[1]
You never read the file but only open it. It should be (beware untested):
void ReadOpenedFile(char* path, HWND hTextBox)
{
// Warning suppressor because it doesn't build without fopen_s it seems.
#pragma warning (disable: 4996)
FILE* f = fopen(path, "rt");
// error test for f == NULL omitted for brievety
char buf[16384]; // adjust per you requirement up to ~32000
size_t sz = fread(buf, 1, sizeof(buf) - 1, f);
buf[sz] = '\0';
SetWindowTextA(hTextBox, buf);
fclose(f);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
