LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Checking file type with fstat (https://www.linuxquestions.org/questions/linux-general-1/checking-file-type-with-fstat-944517/)

Skyrius 05-12-2012 12:14 AM

Checking file type with fstat
 
So I'm trying to figure out how to work this, but I'm not getting anywhere. We have an assignment where we have to sort a file we get from stdin. Part of the requirement is that we have to use fstat to get information about the file. Mainly, if it's a regular file or not. If it is, we have to allocate enough memory with malloc to store it.

The problem I'm having is figuring out how to get fstat to work correctly. I know that there's a macros S_ISREG(m) that we can check using the st_mode field...? How...?

Is it a bool and how do I even access it? The problem is I can find all these documents explaining WHAT all the things are, but not how to use them. Basically, I have:

Code:

struct stat buffer;
int status;
int size;
status = fstat(0, &buffer);
size = buffer.st_size;

That stores the stat struct with all the information. What I need is something that will let me do something like this:

Code:

if(/*is a regular file*/)
  malloc(size);
else
  do something else;

The problem being I don't think I'm even storing size correctly and I'm not sure how to use the st_mode field :\

kbp 05-12-2012 06:35 AM

Try 'man fstat' and take a look at the switch block in the example near the bottom.

Quote:

Code:

          switch (sb.st_mode & S_IFMT) {
          case S_IFBLK:  printf("block device\n");            break;
          case S_IFCHR:  printf("character device\n");        break;
          case S_IFDIR:  printf("directory\n");              break;
          case S_IFIFO:  printf("FIFO/pipe\n");              break;
          case S_IFLNK:  printf("symlink\n");                break;
          case S_IFREG:  printf("regular file\n");            break;
          case S_IFSOCK: printf("socket\n");                  break;
          default:      printf("unknown?\n");                break;
          }




All times are GMT -5. The time now is 07:24 AM.