0
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.

2
  • Standard Warning : Please do not cast the return value of malloc() and family in C. Commented Jun 12, 2015 at 13:32
  • Remove the unnecessary fflush call and add a call to fclose before returning from IspisMatriceUDatoteku, as LoztInSpace said in his answer. Commented Jun 12, 2015 at 13:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Glad to see the old C magic is still there after 20 years :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.