开发者

Using the read function to read in a file

开发者 https://www.devze.com 2022-12-28 05:42 出处:网络
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.

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


  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?


== has higher precedence than =:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号