tags:

views:

80

answers:

2

Hello,

gcc 4.4.1

I am using the read function to read in a wave file. However, when it gets to the read function. Execution seems to stop and freezes. I am wondering if I am doing anything wrong with this.

The file size test-short.wave is: 514K.

What I am aiming for is to read the file into the memory buffer chunks at a time. Currently I just testing this.

Many thanks 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 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;
}
+3  A: 

== has higher precedence than =:

if((fd = open(filename, O_RDWR)) == -1)
Ignacio Vazquez-Abrams
+5  A: 
  1. You assign pointer to the char, not char*.
  2. You read sizeof(char) (likely 1 byte), not 10240.
  3. You read the data into whatever buff, converted to pointer, points to, not into buff.
  4. The precedence issue mentioned by Ignacio Vazquez-Abrams is still relevant.
  5. You call strlen() on char, which doesn't make much sense. Even less before populating what is supposed to be buffer.
  6. You assign const char * (string literal) to char*.

Aren't compiler warnings swarming around this code?

Michael Krelin - hacker
I have made the corrections. Actually I compile with the following -Wall -Wextra -ggdb
robUK
I would expect edited code to work. That is, give your 10240, 0 and 10240 (provided that the file is bigger and, according to you, it is) in the output.
Michael Krelin - hacker