Sunday, 11 August 2013

Maximum Array Size in C

Maximum Array Size in C

I wrote a program to read a text file, send all file content to a message
queue, and display in the console. The size of the text files I have is
ranged from 30kb to 30mb. Now my program can only read up to 1024 bytes.
What number should I set MAX in order to read all the file contents? Or is
the problem in somewhere else? Please advise. Your help is greatly
appreciated.
#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);
}

No comments:

Post a Comment