caot
caot

Reputation: 3318

How to make the c code compiled?

Here is a sample c code related to stat.h. bits/stat.h that mentioned "Never include <bits/stat.h> directly; use <sys/stat.h> instead.". However struct stat is defined in bits/stat.h, and int __xstat (...) is defined in sys/stat.h. The code won't compile with any one of headers or even both of them. How to make it copiled while only changing the #include ... without changing any one of the functions?

#include <stdio.h>

#include <bits/stat.h>
#include <sys/stat.h>


int stat_1(char *filename, struct stat *stat_buf)
{
  return __xstat(1, filename, stat_buf);  //  extern int __xstat (...) defined in sys/stat.h
}

char * test(const char *filename) {
    char *result;
    stat stat_buf;        //  struct stat defined in bits/stat.h

    printf("DO something here");

    if ( stat_1(filename, &sbuf) == -1 ) {
        printf("DO something here");
    }

    return result;
}


int main() {
    const char *fileName = "file.txt";
    test(fileName);

    return 0;
}

Upvotes: 0

Views: 144

Answers (2)

Joe
Joe

Reputation: 42577

For stat and its associated struct, you should likely be includeing:

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

Upvotes: 1

pm100
pm100

Reputation: 50100

You should be calling stat see https://linux.die.net/man/2/stat. Not __xstat.

Interacting with names that start with __ is almost always a sign you are doing something wrong. They are under the hood implementation things

Upvotes: 5

Related Questions