Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the read function to read in a file

Tags:

c

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;
}
like image 733
ant2009 Avatar asked Feb 15 '26 14:02

ant2009


2 Answers

  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?

like image 143
Michael Krelin - hacker Avatar answered Feb 18 '26 02:02

Michael Krelin - hacker


== has higher precedence than =:

if((fd = open(filename, O_RDWR)) == -1)
like image 35
Ignacio Vazquez-Abrams Avatar answered Feb 18 '26 03:02

Ignacio Vazquez-Abrams