Below is part of my code to read data from a text file, strip out the HTML and print out just the normal text. This all work swell but i am having a problem with reading all of the text file. How would i read the entire text file, understand that i will probably need to use malloc but am unsure of how to do so.
int i, nRead, fd;
int source;
char buf[1024];
int idx = 0;
int opened = 0;
if((fd = open("data.txt", O_RDONLY)) == -1)
{
printf("Cannot open the file");
}
else
{
nRead = read(fd, buf, 1024);
printf("Original String ");
for(i=0; i<nRead; i++)
{
printf("%c", buf[i]);
}
printf("\nReplaced String ");
for(i=0; i<nRead; i++)
{
if(buf[i]=='<') {
opened = 1;
} else if (buf[i] == '>') {
opened = 0;
} else if (!opened) {
buf[idx++] = buf[i];
}
//printf("%c", buf[i]);
}
}
buf[idx] = '\0';
printf("%s\n", buf);
close(source);
If you want to read the complete file do the following:
fstat– see fstat – to get the sizemallocthe buffer i.e.buffer = malloc(fileStats.st_size);fread(buffer, fileStats.st_size, 1);You may wish to add one to the buffer size to place the null character into it.