C – File management, unable to obtain desired output

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error C – File management, unable to obtain desired output on this date .

I am working on my school assignment and I’ve come across my first major hurdle… I am unable to write to a file or even retrieve input using scanf and fgets.

Problem 1:

FILE *f1;
char date_trans[100][15];
    f1 = fopen("test.txt", "w");

if (f1 == NULL)
    printf("File could not be opened.n");

else
    printf("Enter details (sender, receiver, amount.)n");

    for(i = 0; i <= element; i++)
    {
        for(j = 0; j <= 20; j++)
            fgets(date_trans[i][j], 15, stdin);
            printf("%s", date_trans[i][j]);
    }
    fclose(f1);  

This is a small snippet; with the above code I am unable to retrieve the input entered and print it out on display/to a file.

My intent is to have 100 strings and up to 15 characters each.

So say if I were to enter a date like 18/12/15 or like 18-12-15, or a word like “Daniel”, the program stops abruptly for a few seconds after I press enter and then proceeds to display “Press any key…”.

I also receive this error…

[Warning] ...assignmenttest.c:22: warning: passing arg 1 of `fgets' makes pointer from integer without a cast

which I really do not understand as the variable date_trans is a string/an 2d array of characters, not an integer, right?


Edit:

Problem 2:

    for (j=0; j <= 50 || !feof(f1); j++); // f1 opened in 'r' mode.
        {
            fscanf(f1, "%s %d %s %d %s %f", date_trans[j], &accsend[j], accnames[j],
            &accreceive[j], accnamer[j], &amount_trans[j]);
            printf("%d %s %d %s %d %s %.2fn", j+1, date_trans[j], accsend[j], accnames[j], 
            accreceive[j], accnamer[j], amount_trans[j]); 
        }

In the code above, I am trying to input data through the stream f1 with function fscanf, which was opened in read mode. However the output makes the program hang and I am also unable to type or do any actions within the program.

As well, please advise whether my usage of !feof is correct/appropriate.

Thanks for any help.

Answer

I see two problems with the code you show:

  1. The warning you get, because date_trans[i][j] is a char, not a char *
  2. Your inner loop goes from 0 to 20 (inclusive) and you use that as index into an array with 15 elements (i.e. indexes from 0 to 14 inclusive).

To solve both problems, don’t have the inner loop, instead in the outer do

fgets(data_trans[i], sizeof data_trans[i], stdin);

Problem number 1 also exists in the printf call, where you pass a single char to a format that expects a char *.

Lastly a note about your requirement of strings containing 15 characters: Don’t forget the null-terminator, and its need for a space in the array as well. That means you currently have place for 14 characters plus the terminator.