使用读取功能读取文件
问题描述:
gcc 4.4.1使用读取功能读取文件
我正在使用读取函数来读取波形文件。但是,当它到达阅读功能。执行似乎停止并冻结。我想知道我是否在做这个问题。
文件大小test-short.wave是:514K。
我的目标是一次将文件读入内存缓冲区块。目前我只是测试这个。
非常感谢您的任何建议,
#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;
}
===编辑更正===
#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;
}
答
- 您指定指向0123的指针,而不是
char*
。 - 你读
sizeof(char)
(可能是1字节),而不是10240. - 你把数据读入
buff
,转换成指针,指向,而不是buff。 - Ignacio Vazquez-Abrams提到的优先级问题仍然相关。
- 您在char上调用
strlen()
,这没有多大意义。在填充什么应该是缓冲区之前更少。 - 您将
const char *
(字符串文字)分配为char*
。
是不是编译器警告蜂拥周围此代码?
+0
我做了更正。其实我编译以下-Wall -Wextra -ggdb – ant2009 2010-04-28 15:33:53
+0
我希望编辑的代码工作。也就是说,在输出中给10240,10和10240(假设文件比较大,按照你的意思)。 – 2010-04-28 18:10:02
答
==
的优先级高于=
:
if((fd = open(filename, O_RDWR)) == -1)
咳嗽libsndfile咳嗽 – 2010-04-28 14:09:48