UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2007-08-13 03:28 AM

zhn636
Member
Registered: 2007-04-24
Posts: 146

Re: fread

I want to use the fread() function to read line by line in a  txt file, how can I do?

Offline

#2 2007-08-13 06:54 AM

drs
Member
Registered: 2006-10-06
Posts: 12

Re: fread

Offline

#3 2007-08-13 07:54 AM

zhn636
Member
Registered: 2007-04-24
Posts: 146

Re: fread

can anybody give me a whole example that  read a txt file line by line?
thanks

Offline

#4 2007-08-13 10:20 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: fread

There's also getline(), if you don't mind GNUism. It can allocate the memory for you.

Offline

#5 2007-08-14 07:36 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: fread

#include <stdio.h>

int main(int argc, char ** argv)
{
   FILE * in;
   char buf[1024];   /* maximum length of a line of text supported by this program */
   int lineNumber = 0;

   if (argc <= 1)
   {
      printf("Usage:  readfile <filename>\n");
      return 10;
   }
   in = fopen(argv[1], "r");
   if (in == NULL)
   {
      printf("Error, couldn't open file [%s]\n", argv[1]);
      return 10;
   }

   while(fgets(buf, sizeof(buf), in) != NULL) printf("Line #%i was: %s", ++lineNumber, buf);
   fclose(in);

   return 0;
}

Offline

#6 2007-08-15 02:17 AM

zhn636
Member
Registered: 2007-04-24
Posts: 146

Re: fread

Offline

#7 2007-08-15 02:26 AM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: fread

Offline

#8 2007-08-15 02:35 AM

zhn636
Member
Registered: 2007-04-24
Posts: 146

Re: fread

and if I allocate a big memory when I do not know how many character a line ,whether we waste the extra memory? whether we can allocate the memory dynamicly? thanks

Offline

Board footer

Powered by FluxBB