Thread: get length of a stream

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    stdin is a stream, so it isn't seekable. If you want to know its length, you must read data until you get EOF. If you need to DO something with that data, you need to store it somehow since it will be lost as you read it.

    One possibility is to copy the data to a temporary file as you read it in. Then you can open this file and seek in it.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    37
    A simple solution would be:

    Code:
    char buff[1024];
    int len = 0;
    
    //Open the filename passed as argument int the main (argv[])
    FILE *file = fopen(filename.txt, "r");    //open file
    while(fgets(buff, 1024, file) != NULL) {  //read each line untill eof
         len += strlen(buff);    //add the number of characters of each line
    }
    
    printf("Size of file is: %d\n", len);  //print the size as the result

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. Strange string behavior
    By jcafaro10 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 07:38 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Weird modification to string length
    By ChwanRen in forum C Programming
    Replies: 0
    Last Post: 08-17-2003, 10:45 AM
  5. length of string etc.
    By Peachy in forum C Programming
    Replies: 5
    Last Post: 09-27-2001, 12:04 PM