我编写了一个程序来读取文本文件,将所有文件内容发送到消息队列,并在控制台中显示。我拥有的文本文件的大小从 30kb 到 30mb 不等。现在我的程序最多只能读取 1024 个字节。为了读取所有文件内容,我应该设置什么数字?还是其他地方的问题?请指教。非常感谢您的帮助。
#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);
}