c - Using the read function to read in a file -
gcc 4.4.1
i using read function read in wave file. however, when gets read function. execution seems stop , freezes. wondering if doing wrong this.
the file size test-short.wave is: 514k.
what aiming read file memory buffer chunks @ time. testing this.
many suggestions,
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> int main(void) { char buff = malloc(10240); int32_t fd = 0; int32_t bytes_read = 0; char *filename = "test-short.wav"; /* open wave file */ if((fd = (open(filename, o_rdwr)) == -1)) { fprintf(stderr, "open [ %s ]\n", strerror(errno)); return 1; } printf("opened file [ %s ]\n", filename); printf("sizeof(buff) [ %d ]\n", sizeof(buff)); bytes_read = read(fd, buff, sizeof(buff)); printf("bytes read [ %d ]\n", bytes_read); return 0; }
=== edit corrections ===
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> int main(void) { char buff[10240] = {0}; int32_t fd = 0; int32_t bytes_read = 0; const char *filename = "test-short.wav"; fd = open(filename, o_rdwr); if(fd == -1) { fprintf(stderr, "open [ %s ]\n", strerror(errno)); return 1; } printf("sizeof(buff) [ %d ]\n", sizeof(buff)); printf("strlen(buff) [ %d ]\n", strlen(buff)); bytes_read = read(fd, buff, sizeof(buff)); printf("bytes read [ %d ]\n", bytes_read); return 0; }
- you assign pointer
char
, notchar*
. - you read
sizeof(char)
(likely 1 byte), not 10240. - you read data whatever
buff
, converted pointer, points to, not buff. - the precedence issue mentioned ignacio vazquez-abrams still relevant.
- you call
strlen()
on char, doesn't make sense. less before populating supposed buffer. - you assign
const char *
(string literal)char*
.
aren't compiler warnings swarming around code?
Comments
Post a Comment