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

sterpa
  • 1
  • 3
  • Check with this [thread](https://stackoverflow.com/questions/14089514/string-initialization-in-multidimensional-array) – Ptit Xav Dec 23 '21 at 14:51
  • The error from the compiler tells you the fwrite call is wrong. You are passing a char where a pointer is required. – stark Dec 23 '21 at 15:41

3 Answers3

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

tony_merguez
  • 307
  • 2
  • 11
0

fwrite first and third parameters are 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);
Mathieu
  • 8,840
  • 7
  • 32
  • 45
0

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.