Using the read function to read in a file

gcc 4.4.1

I am using the read function to read in a wave file. However, when it goes to read function. The execution seems to stop and freeze. I am wondering if I am doing something wrong with this.

Test-short.wave file size: 514K.

What I am aiming for is to read the file in memory cubes at a time. I am currently just testing this.

Thanks a lot for any 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 fixes ===

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

      

+2


a source to share


2 answers


  • You are assigning a pointer to char

    , not char*

    .
  • You are reading sizeof(char)

    (probably 1 byte), not 10240.
  • You are reading data into everything buff

    , converted to pointer point to, not buff.
  • The priority issue mentioned by Ignacio Vasquez-Abram is still valid.
  • You are calling strlen()

    on char, which doesn't make much sense. Even less before filling what should be the buffer.
  • You are assigning const char *

    (string literal) to char*

    .


Do compilers warn about this code?

+5


a source


==

has a higher priority than =

:



if((fd = open(filename, O_RDWR)) == -1)

      

+4


a source







All Articles