I try read a story text file using c. the problem is i want one paragraf in one variabel. i am confuse how much i should alocate the buffer size?

#include <stdio.h>  
int main() {    
char buf[255]; <<HOW MUCH SHOULD WE ALOCATE TE BUFFER?
FILE* fp = fopen("somefile.txt","r");    
  if( fp == NULL)    {       
     printf("Can't open the file\n");       
     return 1;    
  }    // read each line of the file    
 
while( fgets(buf,sizeof(buf),1,fp) != NULL)    {       
  // count the lines or do other stuff here    
}    
// close the file    fclose(fp);    return 0; }

:cheesy:(sorry for my bad english, i hope u understand)

Recommended Answers

All 3 Replies

Well, since you're only reading in one line of the file at a time, you should have some idea of how long the lines will be. Choose a buffer size that is large enough to hold these requirements. Since we don't know what files you're planning to read, we can't give a perfect guess.

This question is similar to "how large should I make this field in my database?" Well, the answer is however much you need.

In C++ this problem doesn't exist since you can use strings to dynamically allocate the memory needed to store the data.

you have a couple options: (1) put each of the strings in an array of strings, or (2) keep a linked list of the lines that are read.

Here is an example of using the array.

#include <stdio.h>  
int main() {    
int linecount = 0;
char *array[255] = {0}; // hold 255 lines

char buf[255]; <<HOW MUCH SHOULD WE ALOCATE TE BUFFER?
FILE* fp = fopen("somefile.txt","r");    
  if( fp == NULL)    {       
     printf("Can't open the file\n");       
     return 1;    
  }    // read each line of the file    
 
while( fgets(buf,sizeof(buf),1,fp) != NULL)    {       
  // count the lines or do other stuff here    
   array[linecount] = malloc(strlen(buf)+1);
   strcy(array[linecount],buf);
   linecount++;
}    
// close the file

I try read a story text file using c. the problem is i want one paragraf in one variabel. i am confuse how much i should alocate the buffer size?

Unless you know how many characters in your paragraph, you can't just allocate a buffer. As AD suggests, you can set up an array of pointers, assuming you know how many paragraphs you need. There's another function you can use named realloc() . You malloc() for the first line you read, then realloc() to add more space for each line additional line you read. When you get to the end of the paragraph, increment the paragraph count (like AD did) and start again with a new malloc() .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.