简体   繁体   English

缓冲区大小和文件读取

[英]Buffer size and reading from a file

I already asked a similiar question but I think now the problem is different.. Im writing in C on eclipse ,linux machine. 我已经问过一个类似的问题,但我认为现在的问题有所不同。我在Eclipse,Linux机器上用C语言编写。

I need to read the testfile and each time to try with different buffer size... I know I need to run on the buffer several times if the size of the buffer is too small but im not sure how to do this... 我需要读取测试文件,并每次尝试使用不同的缓冲区大小...如果缓冲区的大小太小,我知道我需要在缓冲区上运行几次,但是我不确定如何执行此操作...

this is my code ( when im running on buffer with size 67108864 im getting segmentation fault. * I edited my code 这是我的代码(当即时消息在大小为67108864的缓冲区上运行时,我遇到了分段错误。*我编辑了代码

int main(void)
{   int fd;
    char* buff = malloc (67108864);
    if (buff){
    fd = open("testfile.txt", O_RDONLY);
    if (fd >= 0) {
        while (read(fd,buff,67108864)!=0){}
        close(fd);
    }
    }
free(buff);
return 0;
}

This is not a char[] : 这不是一个char[]

char* buff[67108864];

but is an array of char* . 但是是char*的数组。 Change to: 改成:

char buff[67108864];

Also, the size of buff may be too large for the stack. 另外, buff的大小可能对于堆叠来说太大。 The typical size of the stack is 1MB (1048576 bytes) but the size of buff far exceeds (64MB!) that which would result in a stack overflow error. 堆栈的典型大小为1MB(1048576字节),但buff的大小远远超过(64MB!),这将导致堆栈溢出错误。 If you wish to use a buffer of this dynamically allocate it, using malloc() , and release it later, using free() : 如果您希望使用此缓冲区的缓冲区,请使用malloc()动态分配它,并稍后使用free()释放它:

char* buff = malloc(67108864);
if (buff)
{
    /* Use 'buff' and then release it. */

    free(buff);
}

Remove * , you are declaring an array of pointers, but you need an array of characters. 删除* ,您要声明一个指针数组,但是需要一个字符数组。

   char buff[67108864];

I'm not sure about 67108864 it's too big for stack. 我不确定67108864堆栈太大了。 Try to make it on heap. 尝试使其在堆上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM