user4993811
user4993811

Reputation:

Writing 2D array into a file using function in C

void IspisMatriceUDatoteku(int red, int stupac, int *matrica)
{
    FILE *f;
    char imeDatoteke[50];

    printf("\nUnesite ime datoteke :");
    scanf("%s", imeDatoteke);
    f = fopen(imeDatoteke, "w");

    if(NULL == f)
        printf("Nevalja!!!\n");
    else
    {
        for(int i=0; i<red; i++)
            {
                for(int j=0; j<stupac; j++)
                {
                    fflush(f);
                    fprintf(f, "%d ", matrica[i*stupac+j]);
                }
                fprintf(f ,"\n");
            }
    }
}


 int main()
 {
    int red, stupac;
    int *a=NULL;
    printf("Unesite dimenzije matrice :");//matrix dimensions rows and columns
    scanf("%d %d", &red, &stupac);
    a = (int*)malloc(red* stupac* sizeof(int));

    IspisMatriceUDatoteku(red, stupac, a);
 }

I'm trying to write matrix into a file. If i try to put :

9 8 8 
6 1 8 
4 3 8

into a file using this code i get :

9 8 8 
6 1 8 
4 3 

So my question is how to get that last element into my file using function like this or there is another way to write matrix inside it. Matrix is randomly generated in another function. Thanks.

Upvotes: 0

Views: 696

Answers (1)

LoztInSpace
LoztInSpace

Reputation: 5697

Most likely because you don't close the file. Move your flush() to the end or don't bother & just close the file when you're done.

Upvotes: 1

Related Questions