Reputation: 1
I am trying to write a c++ program to read some data from a file. My code is:
void read_file(const char *foldername) {
FILE *fp;
char c;
const char *filename;
filename=strcat((char *)foldername, "L1_matrix");
fp=fopen(filename, "w+");
if(fp)
while (fgets((char *)c,512,fp))
printf("%s", c);
}
int main() {
read_file("A:\\Project\\Root\\event_1\\");
getchar();
}
I want to read several files like L2_matrix etc.
But in this I am getting several error like:
Access violation location error(I found this error I get in filename)
The variable 'c' is being used without being initialized.
If anybody can help it will be a great help.
Upvotes: 0
Views: 321
Reputation: 45684
strcat((char *)foldername, "L1_matrix");
strcat
takes an in-out parameter pointing to a buffer containing a 0-terminated string, and big enough to store the result, and a pointer to a string.
You give it foldername
and assure it that it actually points to a modifiable buffer by casting.
Don't lie!
Similarly for your second error, but the cast is more egregiously wrong:
fgets((char *)c,512,fp)
This reads the uninitialized variable c
, thus your "without initialization"-warning, which is UB.
Next, you forcibly convert it to a char*
, but never fear: On modern desktops, writing or reading through an integer in the char
-range converted to a pointer will segfault.
Upvotes: 1