Solved

How to read file properties in C ?

Posted on 2004-04-21
11
981 Views
Last Modified: 2008-02-01
I need to read the file properties in C. Specifically, I need to read the times of creation, modification of the file.  Does anyone know which function can achive this in C language? I know the functions suitable for this in Visual Basic, but I don't know how to do it in C.

Thanks in advance for your help.
0
Comment
Question by:yangye
  • 4
  • 3
  • 2
  • +1
11 Comments
 

Accepted Solution

by:
cameron_schuler earned 50 total points
ID: 10882868
The following is from  a man page:

NAME
       stat, fstat, lstat - get file status

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <unistd.h>

       int stat(const char *file_name, struct stat *buf);
       int fstat(int filedes, struct stat *buf);
       int lstat(const char *file_name, struct stat *buf);

DESCRIPTION
       These  functions  return  information  about the specified
       file.  You do not need any access rights to  the  file  to
       get  this  information  but  you need search rights to all
       directories named in the path leading to the file.

       stat stats the file pointed to by file_name and  fills  in
       buf.

       lstat  is  identical to stat, except in the case of a sym­
       bolic link, where the link itself is stat-ed, not the file
       that it refers to.

       fstat  is identical to stat, only the open file pointed to
       by filedes (as returned by open(2)) is stated in place  of
       file_name.


       They  all return a stat structure, which contains the fol­
       lowing fields:


              struct stat {
                  dev_t         st_dev;      /* device */
                  ino_t         st_ino;      /* inode */
                  mode_t        st_mode;     /* protection */
                  nlink_t       st_nlink;    /* number of hard links */
                  uid_t         st_uid;      /* user ID of owner */
                  gid_t         st_gid;      /* group ID of owner */
                  dev_t         st_rdev;     /* device type (if inode device) */                  off_t         st_size;     /* total size, in bytes */
                  unsigned long st_blksize;  /* blocksize for filesystem I/O */
                  unsigned long st_blocks;   /* number of blocks allocated */
                  time_t        st_atime;    /* time of last access */
                  time_t        st_mtime;    /* time of last modification */
                  time_t        st_ctime;    /* time of last change */
              };

       The value st_size gives the size of the file (if it  is  a
       regular file or a symlink) in bytes. The size of a symlink
       is the length of the pathname it contains, without  trail­
       ing NUL.

       The value st_blocks gives the size of the file in 512-byte
       blocks.  (This may be smaller than st_size/512  e.g.  when
       the file has holes.)  The value st_blksize gives the "pre­
       ferred" blocksize for efficient file system I/O.  (Writing
       to a file in smaller chunks may cause an inefficient read-
       modify-rewrite.)

       Not all of the Linux filesystems implement all of the time
       fields.   Some  file system types allow mounting in such a
       way that file accesses do  not  cause  an  update  of  the
       st_atime field. (See `noatime' in mount(8).)

       The  field  st_atime  is changed by file accesses, e.g. by
       exec(2), mknod(2), pipe(2), utime(2) and read(2) (of  more
       than zero bytes). Other routines, like mmap(2), may or may
       not update st_atime.

       The field st_mtime is changed by file modifications,  e.g.
       by  mknod(2),  truncate(2), utime(2) and write(2) (of more
       than zero bytes).  Moreover, st_mtime of  a  directory  is
       changed  by  the  creation  or  deletion  of files in that
       directory.  The st_mtime field is not changed for  changes
       in owner, group, hard link count, or mode.

       The  field  st_ctime  is  changed by writing or by setting
       inode information (i.e., owner, group, link  count,  mode,
       etc.).

       The  following  POSIX macros are defined to check the file
       type:

              S_ISREG(m)  is it a regular file?

              S_ISDIR(m)  directory?

              S_ISCHR(m)  character device?

              S_ISBLK(m)  block device?

              S_ISFIFO(m) fifo?

              S_ISLNK(m)  symbolic link? (Not in POSIX.1-1996.)

              S_ISSOCK(m) socket? (Not in POSIX.1-1996.)


etc.
0
 
LVL 2

Expert Comment

by:timbauer
ID: 10883199
If you want to do this in Windows you probably want
GetFileAttributes()
    or
GetFileAttributesEx()
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/getfileattributesex.asp

GetFileAttributesEx
Gives more fine grained information.

All of the file management functions are at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/file_management_functions.asp

Hope this helps
- Tim
0
 
LVL 2

Assisted Solution

by:timbauer
timbauer earned 20 total points
ID: 10883280
//Here is some code to get you started

#include <windows.h>

int main( int argc, char **argv )
{
  //info on this struct is at
  //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/win32_file_attribute_data_str.asp
  WIN32_FILE_ATTRIBUTE_DATA info;
  if( argc<2 ){
    printf("need a filename\n");
    return 1;
  }

  printf("Getting info on file: %s\n",argv[1] );
  if( !GetFileAttributesEx( argv[1], GetFileExInfoStandard, &info ) )
  {
    printf("ERROR code %ld\n", GetLastError() );
    return 1;
  }
  if( (info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY )
  { // the "directory" bit is set.
    printf(" file is a directory\n");
  } else {
    printf(" file is not a directory and is %d bytes\n", info.nFileSizeLow );
  }

  return 0;
}
0
 

Author Comment

by:yangye
ID: 10883412
Thanks cameron_schuler and timbauer. I just need to do it on DOS (standard C), so I think stat() is a suitable one. Now I have a question, how can I print out the time_t value like a string? I.e., the last modified time of the file "st_mttime" is in time_t structure, I need to record that in a file, so I tried to use

char filename[100];
char recordtime[100];
struct stat buf[1000];
......
stat (filename, buf);
strcpy(recordtime, but->st_mttime);

then tried to write the recordtime to a file (I know how to do this).
......

When I debug, stat(filename, buf) was successeed, but strcpy(recordtime, buf->st_mttime) was failed. Any suggestions? Thanks a lot.
0
 

Assisted Solution

by:cameron_schuler
cameron_schuler earned 50 total points
ID: 10883495
I would just use something like:

-----------------------------
char time_string[32];
time_t test;

time_string = sprintf("%04d%02d%02d %02d:%02d:%02d", test.tm_year + 1900, test.tm_mon+1, test.tm_mday, test.tm_hour, test.tm_min, test.tm_sec);
---------------------------

Use sprintf to put the time in a string in the format of your liking then you can use that string to put in the file.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:yangye
ID: 10884152
Thanks everyone.
0
 
LVL 9

Expert Comment

by:ankuratvb
ID: 10885794
In dos ,you can simply use ctime:

#include <stdio.h>
#include <time.h>

int main(void)
{
   time_t t;
   time(&t);
   printf("Today's date and time: %s\n", ctime(&t));
   return 0;
}
0
 

Author Comment

by:yangye
ID: 10888624
ankuratvb, I question is how to read the properties of  a file, such as its created time, modified time, et al, rather than read the current CPU time.  But thank you for the help all the same.
0
 
LVL 9

Expert Comment

by:ankuratvb
ID: 10888931
Hi yangye,

I guess my example got you there.
In the assisted solution,the time used is of the type time_t
>time_t test;

ctime is a function that converts a time_t type to string so you can convert your date-time of creation of ur file into string using ctime().
Thats all.ctime() just simplifies your conversion of time to string.

replace:

>time_string = sprintf("%04d%02d%02d %02d:%02d:%02d", >test.tm_year + 1900, test.tm_mon+1, test.tm_mday, >test.tm_hour, test.tm_min, test.tm_sec);

with

time_string=ctime(&test);
0
 

Author Comment

by:yangye
ID: 10890519
Thanks ankuratvb. You are right. I can use your second comment as an alternative to convert the time to string. I would like to accept your comment as another assistant answer, but since I had accepted answers yesterday, so I have used up the point and couldn't do that again. Sorry about that and thank you for all of your help.
0
 
LVL 9

Expert Comment

by:ankuratvb
ID: 10890549
Glad to be of help....
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

760 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now