File Size Function / Reading txt File Problem

Posted on 2003-11-06
Last Modified: 2012-08-13
Dear All,

I'm trying to find out file size for my input text files.Here are steps that I followed.

1. A text file at location c:\temp\input_files.txt , this file has list of files for which I've to find file size.
    List includes -   c:\temp\test1.txt
Logic Followed -

1. I open file c:\temp\input_files.txt
2. Read first line i.e file for which I want file size.
3. Store this file in an array
4. Pass this file to function which returns File Size.
5. Output file size.
Problem -

My Program always returns file size only for last line in input_files.txt, for rest of them it returns 0, but if I pass in file name having "C:\temp\test1.txt"
format, instead of reading it from input file, it returns correct value.

thanks & regards

Code -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <malloc.h>

#define INPUT_FIL "C:\\temp\\input_files.txt"

long get_filesize(char *FileName);

void main()

      int j=0;
      char inp_file[256];
      char my_file[50][256];
      FILE *fp;
      fp = fopen(INPUT_FIL,"r");

      while(fgets(inp_file,256,fp) != NULL)

             long file_size1 = get_filesize(my_file[0]);
             long file_size2 = get_filesize(my_file[1]);
      long file_size3 = get_filesize(my_file[2]);


long get_filesize(char *FileName)
    struct stat file;
         return file.st_size;

      return 0;
Question by:s_more
LVL 23

Accepted Solution

brettmjohnson earned 250 total points
ID: 9697232
fgets() reads the entire line, including the newline character into the buffer.
stat() is failing because the filename passed contains the newline character,

while(fgets(inp_file,sizeof(inp_file),fp) != NULL)
  int len = strlen(inp_file)-1;
  if (inp_file[len] == '\n')
    (inp_file[len] = '\0';

Expert Comment

ID: 9699279
fgets  appends the  new line character to the string it reads .To resolve this problem find the new line character in the string and replace it
by null


char * line ,*temp;
// fgets the line
temp = strchr(line,'\n');
if(temp)  *temp = '\0';
LVL 10

Expert Comment

ID: 9699989
To add something more

U should use getline() instead of fgets() because of the following reason

Here's the help of fgets()

Function: char * fgets (char *s, int count, FILE *stream)

The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s, adding a null character to mark the end of the string.  You must supply count characters worth of space in s, but the number of characters read is at most count - 1.  The extra character space is used to hold the null character at the end of the string.

If the system is already at end of file when you call fgets, then the contents of the array s are unchanged and a null pointer is returned.  A null pointer is also returned if a read error occurs.  Otherwise, the return value is the pointer s.

If the input data has a null character, you can't tell.  So don't use fgets unless you know
the data cannot contain a null.  Don't use it to read files edited by the user because, if the user inserts a null character, you should either handle it properly or print a clear error message.  We recommend using getline instead of fgets.

getline stores the newline as well as the terminating NULL character in the buffer.  getline () also takes care of if your target buffer is small i.e. If the char * you are using is not allocated the amount of memory required, realloc is used to add the extra amount

When getline is successful, it returns the number of characters read (including the newline, but not including the terminating null).  This value enables you to distinguish null characters that are part of the line from the null character inserted as a terminator.

Function: ssize_t getline (char **lineptr, size_t *n, FILE *stream)
If you set *lineptr to a null pointer, and *n to zero, before the call, then getline allocates the initial buffer for you by calling malloc.

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

LVL 23

Expert Comment

ID: 9702569
I prefer to use fgets() over getline() because fgets() is in the ANSI-C spec and is portable.
For this particular application, fgets() is more than adequate. In nearly all operating systems,
filenames cannot have embedded NUL bytes*.  The maximum filename size is also defined by
FILENAME_MAX in stdio.h, so changing char inp_file[256] to char inp_file[FILENAME_MAX+2]
should solve the input buffer too small problem.

* There are two instances where I have encountered embedded NUL bytes in filenames:
1) UNICODE filename support - although neither fgets, nor getline will handle that unless UTF-8
encoding is used.
2) Classic Mac OS on HFS filesystems.  I have seen cases where third party apps use a leading
NUL byte in a filename to create a hidden file.  This worked because the Mac OS Toolbox used
Pascal string syntax, which allows embedded NULs.  That stuff wreaked havoc with Mac OS X.

Expert Comment

ID: 9718610
Hi s_more,

The problem is that fgets is obtaining a character 10 (carriage return) after the name of your files. Drop this character, as below:

   while(fgets(inp_file,256,fp) != NULL)


        my_file[0][strlen(my_file[0])-1] = 0;
        my_file[1][strlen(my_file[1])-1] = 0;
        my_file[2][strlen(my_file[2])-1] = 0;

        long file_size1 = get_filesize(my_file[0]);
        long file_size2 = get_filesize(my_file[1]);
        long file_size3 = get_filesize(my_file[2]);

       printf("file %s size %d\n", my_file[0], file_size1);
       printf("file %s size %d\n", my_file[1], file_size2);
       printf("file %s size %d\n", my_file[2], file_size3);

and also, change the printf part as above.



Expert Comment

ID: 9761067

some feedback??


Author Comment

ID: 9783189
Dear All,

Thankyou for your replies,it did help me solve the problem.


Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
c language help - file paths 7 147
How to issue a linefeed, pause, and clear screen in UNIX enviroment 3 72
why "." vs "->" 23 120
Problem to scan all sheets 3 105
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question