Home > OS >  Cant write a 2d array on a FILE on C
Cant write a 2d array on a FILE on C

Time:12-24

char arrTypeLabels[3][7]= {{"Random"},{"ASC"},{"DESC"}};
FILE *f;
    f= fopen( "TIMES.txt", "wb");
    if (f == NULL)
    {
    printf("Error! Could not open file\n");
    exit(-1);
    }
    int i,j;
    for(i=0;i<3;i  )
    {
    for(j=0;j<7;j  )
    {
    printf("%c",arrTypeLabels[i][j]);
    fwrite(arrTypeLabels[i][j],sizeof(char),sizeof(arrTypeLabels),f);   
    }
    }
    fclose(f);aenter code here

Im opening the TIMES.txt file but i cant see any output, althought i think my code is right .......................... :/ pls help...

CodePudding user response:

char arrTypeLabels[3][7] = {
    {"Random"},
    {"ASC"},
    {"DESC"}
};
FILE *f = fopen("TIMES.txt", "wb"); //wb is OK
if (f == NULL)
{
    printf("Error! Could not open file\n");
    exit(-1);
}
int i, j;
for (i = 0; i < 3; i  )
{
    for (j = 0; j < 7; j  )
    {
        printf("%c", arrTypeLabels[i][j]);
        fwrite(arrTypeLabels[i]   j, sizeof (char), sizeof (char), f);  //your mistake is here
    }
}
fclose(f);

I don't know how you're even able to copile your code, because in fwrite, the first argument needs to be a pointer, or in your code, you're giving the value.
Also, what you're trying to do is confusing, because it looks like you're trying to write char by char, but you're attempting to write the whole data contained in arrTypeLabels in one fwrite call.

CodePudding user response:

If you just want to write that array to a file, you can make something like :

char arrTypeLabels[3][7]= {{"Random"},{"ASC"},{"DESC"}};
    FILE *f;
    f= fopen( "TIMES.txt", "wb");
    if (f == NULL)
    {
        printf("Error! Could not open file\n");
        exit(-1);
    }
    fwrite(arrTypeLabels,sizeof(char),sizeof(arrTypeLabels),f);
    fclose(f);

or something like :

char arrTypeLabels[3][7]= {{"Random"},{"ASC"},{"DESC"}};
    FILE *f;
    f= fopen( "TIMES.txt", "wb");
    if (f == NULL)
    {
        printf("Error! Could not open file\n");
        exit(-1);
    }
    for (int i = 0; i < 3; i  )
    {
        for (int j = 0; j < 7; j  )
            fwrite(arrTypeLabels[i]   j,sizeof(char),sizeof(char),f);
    }
    fclose(f);

note that the first method is much faster since you don't have to write (to a file i.e into the hard drive) every single character one at a time.

CodePudding user response:

fwrite third parameter is wrong. since you want to write char by char, your line should be fwrite(&buf[i][j], 1,1,f);

Or simplier, use fputc:

 fputc(buf[i][j], f);
  • Related