Take the 2-minute tour ×

In this program I am trying to input text data on a file, but it is not writing properly.

In my main, where I get data I have...

FILE *fp1 = NULL;
fp1 = fopen("accounts.dat", "a+");

printf ("\nEnter an account number (between 1000 and 5999): ");
        accounts[i] = validateaccount();

printf ("Enter title for new account %d: ", accounts2[i]);
        validatestring(accname, &i);
        scan(accounts, accname, &i);

Where "validateaccount()" and "validatestring()" call other functions which is where I get the account / string value. In the

scan(accounts, accname, &i); 

function I am writing the value given from the validate functions into my file.

void scan (int accounts[MAX], char accname[MAX][MAXSTRING], int *i) {

FILE *fp1;


fprintf(fp1, "%d", accounts[*i]);
fprintf(fp1, ":");
fprintf(fp1, "%s\n", accname[*i]);


So the format for my file input should be like


If my account # was 1000, and the name was "First". And the 2nd account inputed was 1200, and "Second"

But what I get is something like:


When I 'cat accounts.dat' ..the 2nd input is ahead of my first input. Why is this?

The problem was that I was doing


every time I called the function when I could have just passed the argument in the file call, after I got rid of that it worked properly.

Fixed it.

share|improve this question
Why do you open the file twice, and not just pass the FILE* into your scan method? –  Xymostech Dec 4 '12 at 22:39
Is that done by, when I call the scan function: scan(accounts, accname, &i, *****) where ***** is the file call? If so, what is the correct parameter to replace the **** with? –  user1877276 Dec 4 '12 at 22:43
Pass in the FILE* with something like scan(accounts, accname, &i, fp1), where the last argument to scan is FILE* fp1. I'm not sure this solves your problem, but you shouldn't be opening the file twice. You should also remember to fclose your file pointer when you're done with it. –  Xymostech Dec 4 '12 at 22:46
You need to use fseek in your program. –  Alberto Bonsanto Dec 4 '12 at 22:47
I passed the file into the functions, this should help make the code cleaner, but this does not fix the original problem I am having –  user1877276 Dec 4 '12 at 22:49

Your Answer



Browse other questions tagged or ask your own question.