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; } 

  1. you assign pointer char, not char*.
  2. you read sizeof(char) (likely 1 byte), not 10240.
  3. you read data whatever buff, converted pointer, points to, not buff.
  4. the precedence issue mentioned ignacio vazquez-abrams still relevant.
  5. you call strlen() on char, doesn't make sense. less before populating supposed buffer.
  6. you assign const char * (string literal) char*.

aren't compiler warnings swarming around code?


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -