Files Ys Calls

Embed Size (px)

Citation preview

  • 8/10/2019 Files Ys Calls

    1/24

    File System Structure

    The Unix file system is a hierarchical structure that allows users to store information

    by name. At the top of the hierarchy is the root directory, which always has the

    name /. A typical Unix file system might look like:

    The location of a file in the file system is called its path. Since the root directory is at

    the top of the hierarchy, all paths start from /. Using the sample file system illustrated

    above, let us determine the path for quiz1.txt:

    All paths start from the root directory, so the path begins with /

    We need to go to the home subdirectory, and the path becomes /home

    In the home directory, we go into the ian subdirectory. The path is now

    /home/ian

    In the ian directory, we go into the cpsc124 subdirectory. The path is now

    /home/ian/cpsc124

    The file quiz1.txt is in the cpsc124 directory. Appending the filename to the

    path, the path becomes /home/ian/cpsc124/quiz1.txt

    Files and Directories

    There are 3 kinds of files: ordinary files (files), directory files (directories), and special

    files.

    Files:Files are containers for data. This data can be anything, including the

    text of a report, an image (picture) of a house, an executable program like a

    word processor, or any arbitrary data. Files are created by users or programs in

    order to save data for future use. For example, a user might save the report she

    wrote using a text editor into a text file, or she might save an image from a

    drawing program into an image file.

  • 8/10/2019 Files Ys Calls

    2/24

    Directories: Each directory contains a number of files. A directory can contain

    other directories, be contained in another directory, or both. A directory that

    contains a file is called that file's parent directory. Similarly, if directory A

    contains directory B, then directory A is directory B's parent directory. A

    directory that is contained in another directory is called a subdirectory.

    Special files: A special file is much like an ordinary file, and shares the same

    basic interface. However, special files are not stored in the file system because

    they represent input/output devices. The I/O device provides the data directly.

    You will not responsible for knowing how special files work or even how to use

    them. Simply be aware that they are present.

    Every file has an associated data structure that contains important information about

    that file. This data structure is known as an i-node. An i-node has information about

    the length of the file, the time the file was most recently modified or accessed, the time

    the i-node itself was most recently modified, the owner of the file, the groupidentifications and access permissions, the number of links to the file (we will discuss

    these shortly), and pointers to the location on the disk where the data contained in

    the file is stored. A filename is used to refer to an i-node. A directory is a file that

    contains a list of names, and for each name there is a pointer to the i-node for the file

    or directory. The following picture offers a graphical interpretation of files, their i-

    nodes, and the blocks that they occupy on disk:

  • 8/10/2019 Files Ys Calls

    3/24

    OPEN SYSTEMCALL:

    Opening or creating a fle can be done using the system open system call.

    #include

    #include

    #include

    Function Definition

    int open(const char *path, int oflags);

    int open(const char *path, int oflags, mode_t mode);

    Field Description

    const char

    *path

    The relative or absolute path to the file

    that is to be opened.

    int oflags

    whether it should be read only,

    read/write, whether it should be cleared

    when opened, etc

    mode_t

    mode

    Modes determine the permissions of the

    file if it is created.

  • 8/10/2019 Files Ys Calls

    4/24

    return

    value1 for ok,-1 on error

    Code Snippet

    Example using the open system call:

    #include

    #include

    int main()

    {

    size_t filedesc = open("testfile.txt", O_WRONLY |

    O_APPEND);

    if(filedesc < 0)

    return 1;

    if(write(filedesc,"This will be output to testfile.txt\n",

    36) != 36)

    { write(2,"There was an error writing to

    testfile.txt\n",43);

    return 1;

    }

    return 0;

    }

    Available Values for oflag

    Value Meaning

    O_RDONLYOpen the file so that it is read only.

    O_WRONLYOpen the file so that it is write only.

  • 8/10/2019 Files Ys Calls

    5/24

    O_RDWR Open the file so that it can be read from and written to.

    O_APPEND Append new information to the end of the file.

    O_TRUNC Initially clear all data from the file.

    O_CREATIf the file does not exist, create it. If the O_CREAT option is used, then you

    must include the third parameter.

    O_EXCLCombined with the O_CREAT option, it ensures that the callermustcreate

    the file. If the file already exists, the call will fail.

    Available Values for mode

    Value Meaning

    S_IRUSR Set read rights for the owner to true.

    S_IWUSRSet write rights for the owner to true.

    S_IXUSR Set execution rights for the owner to true.

    S_IRGRPSet read rights for the group to true.S_IWGRPSet write rights for the group to true.

    S_IXGRPSet execution rights for the group to true.

    S_IROTH Set read rights for other users to true.

    S_IWOTHSet write rights for other users to true.

    S_IXOTH Set execution rights for other users to true.

    READ:

    read is asystem callused to read data into a buffer.

    #include

    Function Definition

    size_t read(int fildes, void *buf, size_t nbytes);

    Field Description

    int fildesThe file descriptor of where to read the input. You can either use a filedescriptor obtained from theopensystem call, or you can use 0, 1, or 2, to

    refer to standard input, standard output, or standard error, respectively.

    const

    void *bufA character array where the read content will be stored.

    size_t

    nbytes

    The number of bytes to read before truncating the data. If the data to be read

    is smaller than nbytes, all data is saved in the buffer.

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:system-calls:openhttp://codewiki.wikidot.com/c:system-calls:openhttp://codewiki.wikidot.com/system-calls
  • 8/10/2019 Files Ys Calls

    6/24

    return

    valueReturns no of bytes on ok,-1 on error

    Code Snippet

    #include

    int main()

    {

    char data[128];

    if(read(0, data, 128) < 0)

    write(2, "An error occurred in the read.\n", 31);

    exit(0);

    }

    WRITE:

    write is asystem callthat is used to write data out of a buffer.

    Required Include Files

    #include

    Function Definition

    size_t write(int fildes, const void *buf, size_t nbytes);

    Field Description

    int fildes

    The file descriptor of where to write the output. You can either use a file

    descriptor obtained from theopensystem call, or you can use 0, 1, or 2, to

    refer to standard input, standard output, or standard error, respectively.

    const

    void *bufA null terminated character string of the content to write.

    size_t

    nbytes

    The number of bytes to write. If smaller than the provided buffer, the output

    is truncated.

    return

    value

    Returns the number of bytes that were written. If value is negative, then the

    system call returned an error.

    Code Snippet

    Example using standard file descriptors:

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:system-calls:openhttp://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:system-calls:open
  • 8/10/2019 Files Ys Calls

    7/24

    #include

    int main(void)

    {

    if (write(1, "This will be output to standard out\n", 36) != 36) {

    write(2, "There was an error writing to standard out\n", 44); return -1;

    }

    return 0;

    }

    Example using a file descriptor:

    #include

    #include

    int main(void)

    {

    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);

    if (filedesc < 0) {

    return -1;

    }

    if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {

    write(2, "There was an error writing to testfile.txt\n", 43); return -1;

    }

    return 0;

    }

    CLOSE:

    close is asystem callthat is used to close an open file descriptor.

    Required Include Files

    #include

    Function Definition

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/system-calls
  • 8/10/2019 Files Ys Calls

    8/24

    int close(int fildes);

    Field Description

    int fildesThe file descriptor to be closed.

    return

    value

    Retuns a 0 upon success, and a -1 upon failure. It is important to check the

    return value, because some network errors are not returned until the file is

    closed.

    Code Snippet

    Example closing an open file descriptor:

    #include

    #include

    int main()

    {size_t filedesc = open("testfile.txt", O_WRONLY | O_CREAT);

    if(filedesc < 0)

    return 1;

    if(close(filedesc) < 0)

    return 1;

    return 0;

    }

    LSEEK:

    lseek is asystem callthat is used to change the location of the read/write pointer of a

    file descriptor. The location can be set either in absolute or relative terms.

    Required Include Files

    #include

    #include

    Function Definition

    off_t lseek(int fildes, off_t offset, int whence);

    Field Description

    int fildes The file descriptor of the pointer that is going to be moved.

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/system-calls
  • 8/10/2019 Files Ys Calls

    9/24

    off_t

    offsetThe offset of the pointer (measured in bytes).

    int

    whence

    The method in which the offset is to be interpreted (relative, absolute, etc.).

    Legal values for this variable are provided at the end.

    return

    value

    Returns the offset of the pointer (in bytes) from thebeginningof the file. If

    the return value is -1, then there was an error moving the pointer.

    Code Snippet

    The following is an example using the lseek system call.

    #include

    #include

    #include

    int main(){

    int file=0;

    if((file=open("testfile.txt",O_RDONLY)) < -1)

    return 1;

    char buffer[19];

    if(read(file,buffer,19) != 19) return 1;

    printf("%s\n",buffer);

    if(lseek(file,10,SEEK_SET) < 0) return 1;

    if(read(file,buffer,19) != 19) return 1;

    printf("%s\n",buffer);

    return 0;

    }

    The output of the preceding code is:

    $ cat testfile.txt

    This is a test file that will be usedto demonstrate the use of lseek.

    $ ./testing

    This is a test file

    test file that will

    Available Values for whence

  • 8/10/2019 Files Ys Calls

    10/24

    Value Meaning

    SEEK_SETOffset is to be measured in absolute terms.

    SEEK_CUROffset is to be measured relative to the current location of the pointer.

    SEEK_ENDOffset is to be measured relative to the end of the file

    STAT:

    stat is asystem callthat is used to determine information about a file based on its file

    path.

    Required Include Files

    #include

    #include

    #include

    Function Definition

    int stat(const char *path, struct stat *buf);

    Field Description

    const char

    *pathThe file descriptor of the file that is being inquired.

    struct stat

    *buf

    A structure where data about the file will be stored. A detailed look at all of

    the fields in this structure can be found in thestruct statpage.

    return

    value Returns a negative value on failure.

    Code Snippet

    An example of code that uses the stat() system call is below.

    #include

    #include

    #include

    #include

    int main(int argc, char **argv)

    {

    if(argc != 2)

    return 1;

    struct stat fileStat;

    if(stat(argv[1],&fileStat) < 0)

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:struct-stathttp://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:struct-stat
  • 8/10/2019 Files Ys Calls

    11/24

    return 1;

    printf("Information for %s\n",argv[1]);

    printf("---------------------------\n");

    printf("File Size: \t\t%d bytes\n",fileStat.st_size);

    printf("Number of Links: \t%d\n",fileStat.st_nlink);printf("File inode: \t\t%d\n",fileStat.st_ino);

    printf("File Permissions: \t");

    printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");

    printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");

    printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");

    printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");

    printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");

    printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");

    printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");

    printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");

    printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");

    printf("\n\n");

    printf("The file %s a symbolic link\n", (S_ISLNK(fileStat.st_mode)) ? "is" : "is not");

    return 0;

    }

    The output of this program is shown in the following set of commands:

    Information on the current files in the directory:

    $ ls -l

    total 16

    -rwxr-xr-x 1 stargazer stargazer 36 2008-05-06 20:50 testfile.sh

    -rwxr-xr-x 1 stargazer stargazer 7780 2008-05-07 12:36 testProgram

    -rw-r--r-- 1 stargazer stargazer 1229 2008-05-07 12:04 testProgram.c

    Running the program with the file testfile.sh

    $ ./testProgram testfile.sh

    Information for testfile.sh

    ---------------------------

    File Size: 36 bytes

    Number of Links: 1

  • 8/10/2019 Files Ys Calls

    12/24

    File inode: 180055

    File Permissions: -rwxr-xr-x

    The file is not a symbolic link

    Running the program with the files testProgram.c

    $ ./testProgram testProgram.c

    Information for testProgram.c

    ---------------------------

    File Size: 1229 bytes

    Number of Links: 1

    File inode: 295487

    File Permissions: -rw-r--r--

    The file is not a symbolic link

    FSTAT:

    fstat is asystem callthat is used to determine information about a file based on its file

    descriptor.

    Required Include Files

    #include

    #include #include

    Function Definition

    int fstat(int fildes, struct stat *buf);

    Field Description

    int fildes The file descriptor of the file that is being inquired.

    struct stat

    *buf

    A structure where data about the file will be stored. A detailed look at all of

    the fields in this structure can be found in thestruct statpage.

    returnvalue

    Returns a negative value on failure.

    Code Snippet

    An example of code that uses the fstat() system call is below.

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:struct-stathttp://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:struct-stat
  • 8/10/2019 Files Ys Calls

    13/24

    #include

    #include

    #include

    #include

    #include

    int main(int argc, char **argv)

    {

    if(argc != 2)

    return 1;

    int file=0;

    if((file=open(argv[1],O_RDONLY)) < -1)

    return 1;

    struct stat fileStat;if(fstat(file,&fileStat) < 0)

    return 1;

    printf("Information for %s\n",argv[1]);

    printf("---------------------------\n");

    printf("File Size: \t\t%d bytes\n",fileStat.st_size);

    printf("Number of Links: \t%d\n",fileStat.st_nlink);

    printf("File inode: \t\t%d\n",fileStat.st_ino);

    printf("File Permissions: \t");

    printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");

    printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");

    printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");

    printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");

    printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");

    printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");

    printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");

    printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");

    printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");

    printf("\n\n");

    printf("The file %s a symbolic link\n\n", (S_ISLNK(fileStat.st_mode)) ? "is" : "is not");

    return 0;

    }

    The output of this program is shown in the following set of commands:

  • 8/10/2019 Files Ys Calls

    14/24

    Information on the current files in the directory:

    $ ls -l

    total 16

    -rwxr-xr-x 1 stargazer stargazer 36 2008-05-06 20:50 testfile.sh

    -rwxr-xr-x 1 stargazer stargazer 7780 2008-05-07 12:36 testProgram-rw-r--r-- 1 stargazer stargazer 1229 2008-05-07 12:04 testProgram.c

    Running the program with the file testfile.sh

    $ ./testProgram testfile.sh

    Information for testfile.sh

    ---------------------------

    File Size: 36 bytes

    Number of Links: 1

    File inode: 180055

    File Permissions: -rwxr-xr-x

    The file is not a symbolic link

    Running the program with the files testProgram.c

    $ ./testProgram testProgram.c

    Information for testProgram.c

    ---------------------------File Size: 1229 bytes

    Number of Links: 1

    File inode: 295487

    File Permissions: -rw-r--r--

    The file is not a symbolic link

    DUP:

    dup is asystem callsimilar todup2in that it creates an alias for the provided filedescriptor. dup always uses the smallest available file descriptor. Thus, if we called

    dup first thing in our program, then you could write to standard output by using file

    descriptor 3 (dup uses 3 because 0, 1, and 2 are already taken by default). You can

    determine the value of the new file descriptor by saving the return value from dup

    Required Include Files

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:system-calls:dup2http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:system-calls:dup2
  • 8/10/2019 Files Ys Calls

    15/24

    #include

    Function Definition

    int dup(int fildes);

    Field Description

    int fildesThe file descriptor that you are attempting to create an alias for.

    return

    value

    dup returns the value of the new file descriptor that it has created (which will

    always be the smallest available file descriptor). A negative return value

    means that an error occured.

    Code Snippet

    Using dup(), we can create an alias for standard output, as follows:

    #include /*Included for dup(2) and write(2)*/

    #include /*Included for exit(3)*/

    #define MESSAGE "Hey! Who redirected me?\r\n\0"

    int main()

    {

    int newfd = dup(STDOUT_FILENO); /*Call dup for an aliased fd*/

    char buff[] = MESSAGE;

    if (newfd < 0) { /*Negative file descriptors are errors*/

    exit(EXIT_FAILURE);

    }

    else if (write(newfd, buff, sizeof(buff)) < 0) { /*See: man 2 write*/

    exit(EXIT_FAILURE);

    }

    return EXIT_SUCCESS;

    }

    You can also use dup() to redirect standard output by taking advantage of the fact thatit always uses the smallest available file descriptor:

    #include

    #include

    #include

    #include

  • 8/10/2019 Files Ys Calls

    16/24

    #include

    #define OUTPATH "output"

    #define MESSAGE "Behold, Standard Out is now a file!"

    int main()

    {

    /*First, we open a file for writing only"*/

    int outputfd = -1;

    outputfd = open(OUTPATH, O_WRONLY | O_CREAT | O_TRUNC,

    S_IRWXU | S_IRGRP | S_IROTH);

    /*If we have an error, we exit

    * N.B. file descriptors less than one are invalid*/if (outputfd < 0) {

    perror("open(2) file: " OUTPATH);

    exit(EXIT_FAILURE);

    }

    /*Next, we close Standard Out

    The lowest file descriptor will now

    be STDOUT_FILENO*/

    if (close(STDOUT_FILENO) < 0) {

    perror("close(2) file: STDOUT_FILENO");

    close(outputfd); exit(EXIT_FAILURE);

    }

    /*Afterwards, we duplicate outputfd onto STDOUT_FILENO,

    exiting if the descriptor isn't equal to STDOUT_FILENO*/

    if (dup(outputfd) != STDOUT_FILENO) {

    perror("dup(2)");

    close(outputfd); /*N.B. Remember to close your files!*/

    exit(EXIT_FAILURE);

    }

    close(outputfd); /*If everything succeeds, we may close the original file*/

    puts(MESSAGE); /*and then write our message*/

    return EXIT_SUCCESS;

    }

  • 8/10/2019 Files Ys Calls

    17/24

    DUP2:

    dup2 is asystem callsimilar todupin that it duplicates one file descriptor, making

    them aliases, and then deleting the old file descriptor. This becomes very useful when

    attempting to redirect output, as it automatically takes care of closing the old file

    descriptor, performing the redirection in one elegant command. For example, if youwanted to redirect standard output to a file, then you would simply call dup2,

    providing the open file descriptor for the file as the first command and 1 (standard

    output) as the second command.

    Required Include Files

    #include

    Function Definition

    int dup2(int fildes, int fildes2);

    Field Description

    int fildes The source file descriptor. This remains open after the call to dup2.

    int fildes2The destination file descriptor. This file descriptor will point to the same file

    as filedes after this call returns.

    return

    value

    dup2 returns the value of the second parameter (fildes2) upon success. A

    negative return value means that an error occured.

    Code Snippet

    Using dup2(), we can redirect standard output to a file, as follows:

    #include

    #include

    #include

    using namespace std;

    int main()

    {

    //First, we're going to open a file

    int file = open("myfile.txt", O_APPEND | O_WRONLY);

    if(file < 0) return 1;

    //Now we redirect standard output to the file using dup2

    if(dup2(file,1) < 0) return 1;

    http://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:system-calls:duphttp://codewiki.wikidot.com/system-callshttp://codewiki.wikidot.com/c:system-calls:dup
  • 8/10/2019 Files Ys Calls

    18/24

  • 8/10/2019 Files Ys Calls

    19/24

    w+ : Open for reading and writing. The file is created if it does not exist,

    otherwise it is truncated. The stream is positioned at the beginning of the file.

    a : Open for appending (writing at end of file). The file is created if it does not

    exist. The stream is positioned at the end of the file.

    a+ : Open for reading and appending (writing at end of file). The file is created if

    it does not exist. The initial file position for reading is at the beginning of the

    file, but output is always appended to the end of the file.

    The fopen() function returns a FILE stream pointer on success while it returns NULL in

    case of a failure.

    fread() and fwrite()

    size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

    size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

    The functions fread/fwrite are used for reading/writing data from/to the file opened by

    fopen function. These functions accept three arguments. The first argument is a

    pointer to buffer used for reading/writing the data. The data read/written is in the

    form of nmemb elements each size bytes long.

    In case of success, fread/fwrite return the number of bytes actually read/written

    from/to the stream opened by fopen function. In case of failure, a lesser number of

    byes (then requested to read/write) is returned.

    fseek()

    int fseek(FILE *stream, long offset, int whence);

    The fseek() function is used to set the file position indicator for the stream to a new

    position. This function accepts three arguments. The first argument is the FILE stream

    pointer returned by the fopen() function. The second argument offset tells the amount

    of bytes to seek. The third argument whence tells from where the seek of offset

    number of bytes is to be done. The available values for whence are SEEK_SET,

    SEEK_CUR, or SEEK_END. These three values (in order) depict the start of the file,

    the current position and the end of the file.

    Upon success, this function returns 0, otherwise it returns -1.

    fclose()

    int fclose(FILE *fp);

  • 8/10/2019 Files Ys Calls

    20/24

    The fclose() function first flushes the stream opened by fopen() and then closes the

    underlying descriptor. Upon successful completion this function returns 0 else end of

    file (eof) is returned. In case of failure, if the stream is accessed further then the

    behavior remains undefined.

    The code

    #include

    #include

    #define SIZE 1

    #define NUMELEM 5

    int main(void)

    {FILE* fd = NULL;

    char buff[100];

    memset(buff,0,sizeof(buff));

    fd = fopen("test.txt","rw+");

    if(NULL == fd)

    {

    printf("\n fopen() Error!!!\n");

    return 1;

    }

    printf("\n File opened successfully through fopen()\n");

    if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))

    {

    printf("\n fread() failed\n");

    return 1;

    }

    printf("\n Some bytes successfully read through fread()\n");

    printf("\n The bytes read are [%s]\n",buff);

    if(0 != fseek(fd,11,SEEK_CUR))

    {

    printf("\n fseek() failed\n");

  • 8/10/2019 Files Ys Calls

    21/24

    return 1;

    }

    printf("\n fseek() successful\n");

    if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd)){

    printf("\n fwrite() failed\n");

    return 1;

    }

    printf("\n fwrite() successful, data written to text file\n");

    fclose(fd);

    printf("\n File stream closed through fclose()\n");

    return 0;

    }

    The code above assumes that you have a test file test.txt placed in the same location

    from where this executable will be run.

    Initially the content in file is :

    $ cat test.txthello everybody

    Now, run the code :

    $ ./fileHandling

    File opened successfully through fopen()

    Some bytes successfully read through fread()

    The bytes read are [hello]

    fseek() successful

    fwrite() successful, data written to text file

    File stream closed through fclose()

  • 8/10/2019 Files Ys Calls

    22/24

    Again check the contents of the file test.txt. As you see below, the content of the file

    was modified.

    $ cat test.txt

    hello everybody

    hello

    Umask

    #include

    #include

    #include

    #include

    int main(void)

    {

    umask(0);

    if (creat("foo", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |

    S_IWOTH) < 0)

    perror("foo");

    umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

    if (creat("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |

    S_IWOTH) < 0)

    perror("bar"); return 0;

    }

    Mkdir:

    #include

    #include

    int main()

    {

    int i;

    char dirname[50];

    for(i=0;i

  • 8/10/2019 Files Ys Calls

    23/24

    {

    sprintf(dirname,"A%d",i);

    if((mkdir(dirname,00777))==-1)

    {

    fprintf(stdout,"error in creating dir\n");

    }

    }

    }

    CHMOD:

    main(){ char mode[4]="0777"; char buf[100]="/home/hello.t"; int i; i = atoi(mode); if (chmod (buf,i) 0) !rintf("error in chmod");

    #$% &o!endir( con't char &dirname );'truct dirent &readdir( #$% &dir! );int readdirr( #$% &dir!, 'truct dirent &entr, 'truct dirent &&re'ult );*oid re+inddir( #$% &dir! );int clo'edir( #$% &dir! );int chdir( con't char &!ath );char &etc+d( char &buf, 'i-et 'i-e );int o!en( con't char & !ath , int ofla , ... );int creat( con't char & !ath, modet mode );int lin( con't char &ei'tin, con't char &ne+ );int mdir( con't char &!ath, modet mode );int unlin( con't char &!ath );int rmdir( con't char &!ath );int rename( con't char &old, con't char &ne+ );int 'tat( con't char &!ath, 'truct 'tat &buf );int f'tat( int fd, 'truct 'tat &buf );int acce''( con't char &!ath, int amode );lon !athconf(con't char &!ath, int name);lon f!athconf(int fd, int name);

    modet uma'( modet cma' );int mfifo( con't char &!ath, modet mode );int chmod( con't char &!ath, modet mode ); // 2int fchmod( int fd, modet mode ); // 2int cho+n( con't char &!ath, uidt o+ner, idt rou! );int utime( con't char &!ath, con't 'truct utimbuf &time' ); // 2int ftruncate( int fd, offt lenth );

  • 8/10/2019 Files Ys Calls

    24/24

    /&& hi' !roram di'!la' the name' of all file' in the current director.

    &/

    3include dirent.h3include 'tdio.h

    int main(*oid){ #$% &d; 'truct dirent &dir; d = o!endir("."); if (d) { +hile ((dir = readdir(d)) 5= 688) {

    !rintf("9':n", dirdname);

    clo'edir(d);

    return(0);