File I/O Operations in C

May 31, 2021 0 Comments

File I/O Operations in C

Command Line Arguments:

File I/O Operations in C, Arguments passed to the main function from the command prompt are considered command-line arguments. signature of the main function is

int main(int argc, char *argv[])

#include<stdio.h>
int main(int argc, char *argv[])
{
        int i;
        printf("%d \n", argc);
        if( argc >= 2 )
        {
                for(i = 0; i < argc; i++)
                {
                        printf("%s ", argv[i]);
                }

                printf("\n");
        }
        else
        {
                printf("you didn't pass any arguments\n");

        }
        return 0;
}

argument 1 in the main function will always hold a number of values passed which includes the executable name.

argument 2 will hold the base address of all the values passed to the main function.

File I/O operations in C:

A file represents a sequence of bytes, regardless of it being a text file or a binary file. A c programming language provides access to high-level functions as well as low-level (OS level) calls to handle files on your storage devices.

fopen:

#include <stdio.h>

FILE *fopen(const char *restrict pathname, const char *restrict mode);

The fopen() function opens the file whose name is the string points to by pathname and associates a stream with it.

The argument mode points to a string beginning with one of the following sequences

r Open text file for reading. The stream is position at the beginning of the file.

r+ Open for reading and writing. The stream is position at the beginning of the file.

w Truncate file to zero length or create text file for writing. The stream is position at the beginning of the file.

w+ Open for reading and writing. The file creates if it does not exist, otherwise, it truncates. The stream is position at the beginning of the file.

a Open for appending (writing at end of file). The file creates if it does not exist. The stream is position at the end of the file.

a+ Open for reading and appending (writing at end of file). The file creates if it does not exist. Output always appends to the end of the file. Upon successful completion fopen() return a FILE pointer. Otherwise, NULL returns an errno set to indicate the error.

fclose:

int fclose(FILE *stream);

The flocse() function flushes the stream pointed to by stream and closes the underlying file descriptor. Upon successful completion, 0 returns. Otherwise, EOF returns an errno set to indicate the error.

fputc:

int fputc(int c, FILE *stream);

fputc() writes the character c, cast to an unsigned char to stream, Upon successful completion, fputc() shall return the value it has written. Otherwise, it shall return EOF, the error indicator for the stream shall be set, and errno shall be set to indicate the error.

fgetc:

int fgetc(FILE *stream);

fgetc() reads the next character from the stream and returns it as an unsigned char cast to an int, or EOF on the end of file or error.

#include<stdio.h>

int main() {
        FILE *fp1,*fp2;
        char c;
        fp1 = fopen("./file.txt","r");
        if(fp1 == NULL) {
                printf("Unable to open file\n");
                return -1;
        }
        fp2 = fopen("./file1.txt","w");
        if(fp2 == NULL) {
                printf("Unable to open file\n");
                return -1;
        }
        while((c = fgetc(fp1)) != EOF) {
                fputc(c,fp2);
                printf("%c", c);
        }
        fclose(fp2);
        fclose(fp1);
        return 0;
}

String/Line I/O Functions:

fputs:

int fputs(const char *restrict s, FILE *restrict stream);

fputs() write the string s to stream, without its terminating NULL byte (‘\0’). fputs() return a nonnegative number on success or return EOF, set an error indicator for the stream

fgets:

char *fgets(char *restrict s, int n, FILE *restrict stream);

The fgets() function shall read bytes from the stream into the array pointed to by s until n-1 bytes are read, or a <newline> is read and transferred to s.

fgets() return s on success, and NULL on error or when the end of file occurs while no characters have been read.

fprintf:

int fprintf(FILE *restrict stream, const char *restrict format, …);

fprintf() write output to the given output stream. Upon successful returns the number of characters printed. If an output error is encountered, a negative value is returned.

fscanf:

int fscanf(FILE *restrict stream, const char *restrict format, …);

fscanf() function reads from the named input stream. Upon successful completion, fscanf function shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure.

#include<stdio.h>
int main() {
        FILE *fp;
        char str[60];
        //fputs example
        fp = fopen("file.txt","a+");
        if(fp == NULL) {
                printf("fopen error\n");
                return -1;
        }
        fputs("kumar",fp);
        fclose(fp);
        //fgets example
        fp = fopen("file.txt","r");
        if(fp == NULL) {
                printf("fopen error\n");
                return -1;
        }
        if(fgets(str,60,fp) != NULL) {
                printf("%s ", str);
        }
        printf("\n");
        fclose(fp);
        //fprintf example
        fp = fopen("file.txt","a+");
        if(fp == NULL) {
                printf("fopen error\n");
                return -1;
        }
        fprintf(fp,"%s %d", "nelavalli", 2021);
        fclose(fp);
        //fscanf exmple
        char str1[30], str2[30], str3[30];
        fp = fopen("file.txt","a+");
        if(fp == NULL) {
                printf("fopen error\n");
                return -1;
        }
        fscanf(fp, "%s %s %s", str1,str2,str3);
        printf("%s %s %s \n",str1, str2, str3);
        fclose(fp);
        return 0;
}

Binary File I/O Functions:

fwrite:

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

The function fwrite() writes nmemb items of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.

fread:

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

The function fread() reads nmemb items of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when the size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

#include<stdio.h>
#include<string.h>
int main() {
        FILE *fp;
        char str[20] = "Welcome to India";
        char buf[20];
        //fwrite example
        fp = fopen("file2.txt","w+");
        if(fp == NULL) {
                printf("fopen error\n");
                return -1;
        }
        fwrite(str,strlen(str)+1, 1, fp);
        fclose(fp);
        //fread example
        fp = fopen("file2.txt","r");
        if(fp == NULL) {
                printf("fopen error\n");
                return -1;
        }
        fread(buf, strlen(str)+1, 1, fp);
        printf("%s \n", buf);
        fclose(fp);
        return 0;
}

File Offset:

Every file which is opened will have a file offset. file offset will tell from which position data should be read from a stream or from which position data should be written into a stream.

The file offset is updated by file I/O functions by a number of bytes processed to or from the stream internally.

fseek:

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

The fseek() function sets the file position indicator for the stream pointed to by stream. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the current position indicator, or end-of-file, respectively.

Upon successful completion, fseek() return 0. Otherwise, -1 return and errno is set to indicate the error.

#include<stdio.h>
#include<string.h>
int main() {
        FILE *fp;
        char str[20] = "Welcome to India";
        char buf[20];
        //fwrite example
        fp = fopen("file2.bin","w+");
        if(fp == NULL) {
                printf("fopen error\n");
                return -1;
        }
        fwrite(str,strlen(str)+1, 1, fp);
        fseek(fp, 0, SEEK_SET);
        fread(buf, strlen(str)+1, 1, fp);
        printf("%s \n", buf);
        fclose(fp);
        return 0;
}

Share This: