-
A Quick One
For the life of me I cant see why this doesnt work! Im trying to read in a 4 by 4 array of integers from a txt file. Any suggestions as to why its not working?
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* pFileHandle;
char filename[15];
int array[4][4];
int i;
int j;
printf("Please enter the name of the file you wish to use:\n");
scanf("%s", filename);
//error test
if((pFileHandle = fopen(filename, "r")) == NULL)
{
printf("Unable to open file : %s\n", filename);
return 0;
}
else
//scan the contents of the input file to the array
{
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
fscanf(pFileHandle, "%i\t", array[i][j]);
}
}
}
fclose(pFileHandle);
}
-
what is in the file? data type
-
FILE* pFileHandle;
try this
FILE *pFileHandle;
-
Nope that didnt work.
The file i used is just a txt file. Its all integers and they're all tab spaced.
1 2 3 4
5 6 7 8
9 8 7 6
5 4 3 2
this basically is the file but with tabs between the numbers and not spaces.
-
Can you try using %d with fscanf() ?
-
its still giving an invalid page fault. im putting the exact path name in "C:\input.txt" and its giving the illegal operation box. If its an incorrect path name it returns the error. Thats working at least!
-
Try putting the path name straight into the program, not using any variables. Remember to use \\ instead of \.
-
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* pFileHandle;
char *filename="C:\\input.txt";
int array[4][4];
int i;
int j;
//printf("Please enter the name of the file you wish to use:\n");
//scanf("%s", filename);
//error test
if((pFileHandle = fopen(filename, "r")) == NULL)
{
printf("Unable to open file : %s\n", filename);
return 0;
}
else
//scan the contents of the input file to the array
{
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
fscanf(pFileHandle, "%d\t", array[i][j]);
}
}
}
fclose(pFileHandle);
}
this is what ive changed it to. I hade to make "filename" into a pointer for it to compile but still its giving the illegal operation. Im not sure if changing it to a pointer was correct though.
-
Oh for heavens sake....
fscanf(pFileHandle, "%d", &array[i][j]);
You don't need the \t, scanf happly ignores leading white space (this includes tabs)
-
Salem you're my hero. Thank you. Thanks for your help aswell Nutshell.