user3433848
user3433848

Reputation: 117

reading from a file and putting in two dimensional buffer

I am trying to read from a file (text) byte wise and putting in sndbuffer. But this is printing some junk . Why so?

Also, since I am learning working with files, so any suggestions regarding improvement in the code is welcomed.

unsigned char sndbuffer[100][1560];
int main()
{
FILE *fp;
unsigned char filename[50];
unsigned char ch;
unsigned int i=0,j=0;
printf("\nEnter file name(with extn)\t");
scanf("%s",filename);
fp=fopen(filename, "r");
while(ch=fgetc(fp))
{
    memcpy(&sndbuffer[i][j],&ch,1);
    printf("%c",sndbuffer[i][j]);
    j=(++j)%1560;

    if(j==0)
    i++;
    if(i==100)
    break;

}

printf("\nOUT OF LOOP");
return 0;
}

Thanks :)

Upvotes: 0

Views: 44

Answers (1)

ajay
ajay

Reputation: 9680

One problem with your code is this statement

unsigned char *filename;

This defines a pointer to an unsigned char, however, you need a char array to store the file name. Change it to

#define MAXLEN 50+1  // +1 for the terminating null byte

char filename[MAXLEN];

Upvotes: 1

Related Questions