In this program I have a file called ‘accounts.dat’ and in this file there are some lines of data like
1000:first
2000:second
3000:third
But when I tried to fscanf the data values into my arrays in my program I get:
0:$ s·°Ïÿ¿
1:t·¨BuÞZ·
-1217025816:s·0s·É¥s·hp[·4£s·
As the values scanned, or at least thats what it’s showing.
My function to scan the values is:
void read (int accounts[MAX], char debcred[MAX], double amount[MAX], char accname[][MAXSTRING], char transname[][MAXSTRING], int *i) {
FILE *fp1 = NULL;
//FILE *fp2 = NULL;
fp1 = fopen("accounts.dat", "r");
//fp2 = fopen("transactions.dat", "r");
int h = 0;
if (fp1 != NULL) // READING THE FILE
{
while(fscanf(fp1, "%d", &accounts[h]) != EOF)
{
fgetc(fp1);
fscanf(fp1, "%30[^\n]", &accname[h]);
h++;
printf("%d:%s\n", accounts[h], accname[h]);
}
fclose(fp1);
}
else
printf ("Failed to open file\n");
}
And how I call my read function in my main is:
read(accounts, debcred, amount, accname, transname, &i);
And my declarations in my main function is:
int accounts[MAX], accounts2[MAX], account;
char debcred[MAX], accname[MAX][MAXSTRING], transname[MAX][MAXSTRING];
double amount[MAX];
Can anyone figure out what my problem is? Why aren’t the data lines in my file being scanned into my arrays in my program properly?
Try incrementing
hafter you print.