Welcome

C Programming Tutorial


C Input and Output


  • Formatted IO
  • File IO

Formatted IO

printf for printing output on Console

    printf function mainly used for printing sequence of characters on console,
printf("hello world!"); it prints string "hello World!" on the screen

Using escape character backslash(\): if you want to print string like this: sam says "I am busy tonight"
printf("sam says \"I am busy tonight\""); // escape character \ removes literal meaning of the character that it follows,here double quotaion(")

  • \n new line character
  • \t horizontal tab
  • \v vertical tab
  • \r carriage return
  • \r form feed

\n new line character
new line character emits string following \n to next line.

printf("hello\nHow are u?");
// prints hello
How are u?

\t horizontal tab
horizontal tab \t emits multiple spaces.

printf("h\te\tl\tl\to");
// prints

 h	e	l	l	o

\v vertical tab
vertical tab \v emits string following it to next line with 1 tab space.

printf("h\ve\vl\vl\vo");
// prints

h
 e
  l
   l
    o

printf conversions
CharacterOutput As
d,isigned decimal notation
ounsigned octal notation(without leading zero)
x,Xunsgined heaxadecimal notation(without leading 0x for x, 0X for X)
uunsigned decimal notation
cSingle character
sprints string until NULL character reached.
fdouble; decimal noation of the form [-]mmm.ddd, where d is the number of d's is given by the precision, Default is 6.precision 0 suppresses the decimal value.
e,E
g,G
pvoid *;print as apointer(implementation dependent)
nThe number of characters written so far by this call to print is written into the argument.
%prints %

scanf for Reading input from keyboard

scanf conversions
CharacterInput Argument As
ddecimal integer
iinteger; the integer can be octal or hexa decimal
ooctal integer(with or without) leading zero
x,Xhexadecimal integer with or without leading 0x,0X
uunsigned decimal integer
cSingle character
sString of non-white space characters(not quoted).char * pointing to an array of character until end of character NULL
e,f,gfloating point number;
ppointer value as printed by the printf("%p")
nThe number of characters written so far by this call to print is written into the argument.
%prints %
%prints %
[...]matches longest non-empty string of input characters from the set between brackets
[^...]matches longest non-empty string of input characters not from the set between brackets

File IO-File Input Output

         Data resides in disks,tapes in terms of files,text files,custom formatted files(word,pdf etc.,). Data can be read,write and transform using c file io functions. C file operations supports text and binary files.programmer should able to read file content,write into a file or append to a file. C file operations can be sequential or random. Sequencial means reading content from the beginning of the file to End of the file sequentially,character by character or line by line. Random access means randomly navigating to any location in the file, start extracting content.

File Functions and their Operations

File FunctionDescription
  fopen  opens file in specified mode for read write and append mode. file can be text or binary file.
  fprintf  prints line of text into file
  fscanf  reads line of text from file
  fgetc,fgets  fgetc gets single character into file stream, fgets - gets line of text into file stream
  fputc,fputs  fputc puts single character into file stream, fputs - puts line of text into file stream
  fwrite  writes file data of specified size from buffer
  fread  reads file data of specified size into buffer
  fclose fcloseall  fclose close the current file pointer stream, fcloseall - closes all streams
  fflush flushall  
  ftell  ftell file pointer position
  rewind  resets file pointer to begining of the file
  fseek  Random access function-moves to desired location in a file
  feof  detects end-of-file

fopen function

fopen is a function, part of stdlib.h .

               FILE *fopen(const char *name, const char *mode);

              fopen function takes 2 arguments , file name and mode of operation, returns file pointer.

Mode of Operations
  mode    meaning  
  r    open text file for read operation
  w    open text file for write operation
  a    open text file for append operation
  rb    open binary file for read operation
  wb    open binary file for write operation
  ab    open binary file for append operation
  r+    open text file for read and write operation
  w+    open text file for write and read operation


A function call to fopen, opens the file based on Mode and returns File Pointer.
File Pointer is a pointer to a structure FILE contains information about the file. That contains information about current read pointer,Current put pointer,reserved area etc., means location of the buffer, current character position in the buffer,whether file is opened for reading or writing, whether errors or end of file have occured. etc.,

typedef struct _IO_FILE FILE; in FILE.h

FILE is a type not a structure tag.




employees.txt contains information about employees
		nirvana ~> cat employees.txt

			Bill Thomas 8000 08/9/1968
			Fred Martin 6500 22/7/1982
			Julie Moore 4500 25/2/1978
			Marie Jones 6000 05/8/1972
			Tom Walker 7000 14/1/1977

	
Reading a file using fopen Example:

#include <stdio.h>

int main(){

    FILE * fp = fopen("employees.txt","r");
    int c;

        while((c=getc(fp))!=EOF){
            printf("%c ",c);
        }
        fclose(fp);
    return 0;
}
	
	
output:
			Bill Thomas 8000 08/9/1968
			Fred Martin 6500 22/7/1982
			Julie Moore 4500 25/2/1978
			Marie Jones 6000 05/8/1972
			Tom Walker 7000 14/1/1977

Writing to a file using fopen Example:

#include <stdio.h>

int main(){

    FILE * fp = fopen("employees.txt","w");
    int c;

        while((c=getc(fp))!=EOF){
            printf("%c ",c);
        }
        fclose(fp);
    return 0;
}
	
	

fseek function - file random access function

     fseek is a random access function,File pointer starts at 0, using fseek function file pointer can be moved/skip N number of bytes

fseek syntax:
		int fseek(FILE* fp, int offset, int origin);
	
fseek origin values:
   Enum Name   Enum Value   Description
   SEEK_SET   0   Moves the file pointer position offset bytes from the beginning of the file.
   SEEK_CUR   1   Moves the file pointer position by offset bytes from current position.
   SEEK_END   2   Moves the file pointer position by offset bytes from the end of the file.

fseek returns 0 for file pointer moved sucessfully or nonzero if error occurs

Read file from last character to first character using fseek function

This example explains how to reverse each number in file called rev.txt, fopen function opens the file in read mode. fseek function goes to end of the file by using option SEEK_END, now file pointer points to one byte past to end of file, that's why used -1 for offset. ftell function tells file pointer position .i.e reading from last byte. fgetc gets character at file pointer position, decrement the offset value by one position. first byte is located at -1

	$ -> cat rev.txt
		123456
		676666
		987655

   FILE *fp = fopen("rev.txt","r");

   fseek(fp,-3,SEEK_END);
   long l=ftell(fp);

   do
   {

    printf("%c",fgetc(fp));

    fseek(fp,l--,0);

   }while(l>=-1);

output:
556789
666676
654321

Count No of Lines a File using `fgetc` function

#include <stdio.h>

int main(){

        FILE *fp = fopen("games-country.txt","r");
        char c;
        int lines =0;
        while( (c=fgetc(fp)) != NULL){
        
        if(c=='\n') ++lines;


        }
        printf("Number of lines = %d\n",lines);
return 0;
}

Count No of Lines a File using `fgets` function

#include <stdio.h>
#define MAXLENGTH 1024

int main(){

        FILE *fp = fopen("games-country.txt","r");
        char buffer[MAXLENGTH];
        int lines =0;

        while( fgets(buffer,MAXLENGTH,fp) != NULL){
        ++lines;
        }

        printf("Number of lines = %d\n",lines);
return 0;
}

Find number of Words in a text file

/*
 * wordEx.c
 *
 *  Created on: 03-Nov-2022
 *      Author: sitapathipurru
 */


#include 
#include 

int main()
{
        FILE *fp = NULL;
        int wcount = 0;
        char c = '\0';
        //games-country.txt
        fp=fopen("txt.txt","r");

        int prev =0;
        while ((c=fgetc(fp))!=EOF){
                if isspace(c)
                {
                   prev=0;
                }
                else if(prev==0){wcount++;prev=1;}
        }

        printf("Number of Words = %d\n",wcount);
        return 0;
}

Reading & Writing into Binary File

      For reading and writing into binary file a pair of functions are provided.

  • For Reading-- size_t fread(void *ptr, size_t size, size_t nobj, FILE *fp);
  • For Writing-- size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *fp);

These 2 functions permit objects of any type to read or written, including Arrays and Structures

ADS