gpt4 book ai didi

c - C 中的最大数组大小

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:22 24 4
gpt4 key购买 nike

我写了一个程序来读取一个文本文件,将所有文件内容发送到一个消息队列,并显示在控制台中。我拥有的文本文件的大小在 30kb 到 30mb 之间。现在我的程序最多只能读取 1024 个字节。我应该设置多少 MAX 才能读取所有文件内容?或者是其他地方的问题?请指教。非常感谢您的帮助。

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define MAX 1024 //1096

//Declare the message structure
struct msgbuf
{
long type;
char mtext[MAX];
};


//Main Function
int main (int argc, char **argv)
{
key_t key; //key to be passed to msgget()
int msgid; //return value from msgget()
int len;
struct msgbuf *mesg; //*mesg or mesg?
int msgflg = 0666 | IPC_CREAT;
int fd;
char buff[MAX];


//Initialize a message queue
//Get the message queue id
key = ftok("test.c", 1);
if (key == -1)
{
perror("Can't create ftok.");
exit(1);
}

msgid = msgget(key, msgflg);
if (msgid < 0)
{
perror("Cant create message queue");
exit(1);
}

//writer
//send to the queue
mesg=(struct msgbuf*)malloc((unsigned)sizeof(struct msgbuf));
if (mesg == NULL)
{
perror("Could not allocate message buffer.");
exit(1);
}

//set up type
mesg->type = 100;

//open file
fd = open(argv[1], O_RDONLY);

while (read(fd,buff,sizeof(buff))>0)
{
//printf("%s\n", buff);
strcpy(mesg->mtext,buff);
}


if(msgsnd(msgid, mesg, sizeof(mesg->mtext), IPC_NOWAIT) == -1)
{
perror("Cant write to message queue");
exit(1);
}


//reader
int n;

while ((n=msgrcv(msgid, mesg, sizeof(mesg->mtext), 100, IPC_NOWAIT)) > 0)
{
write(1, mesg->mtext, n);
printf("\n");

}

//delete the message queue
msgctl(msgid,IPC_RMID,NULL);

close(fd);

}

最佳答案

一次将一个大(数兆字节)文件全部读入堆栈分配的缓冲区是一个坏主意,因为如果缓冲区超过堆栈大小,您将导致堆栈溢出。我相信默认堆栈大小在 Windows 上为 1 MB,在 Linux 上为 8 MB。 (这取决于编译器吗?)

此外,堆栈数组具有固定大小(无论如何在 C89 中),因此您必须猜测最大可能的文件有多大,然后分配一个足够大的缓冲区来容纳它,这可能是非常浪费的。

如果出于某种原因您需要一次将文件全部存储在内存中,您将需要使用 malloc() 堆分配缓冲区。但是,一次在固定大小的缓冲区中对文件的小块进行操作可能更可取。这将允许您安全地在堆栈上分配缓冲区,并且内存效率更高。

关于c - C 中的最大数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com