C Programming IT Programming Tutorials

C Input and Output

In C input and output functions are used to get input data and display the output results, to use those methods it is necessary to include the stdio.h library in our code.

The functions used for standard C input and output operations are

  • scanf() and printf()
  • getchar() and putchar()
  • gets() and puts()

The scanf() and printf() functions

scanf():

The scanf() function is used to read data from the input stream and stores the value according to the given format in the specified variable.

int scanf(const char *format, .....);

Examples:

scanf("%d",&a;)                   // Reads integer value input
scanf("%f",&b)                    // Reads float value input
scanf("%lf %c",&x,&y);      // Reads a double and char values in x and y.

printf():

The printf() function writes the output to the output stream and displays the output according to the specified format.

int printf(const char *format, .....)

Examples:

printf("Enter a value");                           //displays the string 
printf("The value of x is %f and y is %d",x,y);    
                                     //displays x in float and y in integer format
Data Types Format Specifiers
int%d
char%c
float%f
strings%s
double%lf
long double%Lf
signed char, unsigned char%c
short int%hd
long int%li
long long int%lli
unsigned int%u
unsigned long int%lu
unsigned long long int%llu
List Of DataTypes in C

The most commonly used data types are int, float, char, and strings.

The getchar() and putchar() functions

These are known as unformatted functions since it handles only characters.

getchar():

It reads only a single character using the getchar() function from the console and returns an integer value.

int getchar();

putchar():

It puts or displays a single character on the console and returns an integer value.

int putchar(int);

The gets() and puts() functions:

gets():

The gets() function reads strings and stores it in a character array until it finds the new line without boundary check. This causes overflow which can be eliminated by using fgets().

char[] gets(char[])

puts():

The puts() displays the string and returns an integer value. The integer value represents the number of characters in the string. The puts() usually prints the string along with a new line and hence the value returned will be 1 greater than the number of characters in the string.

int puts(char[])

File I/O:

Another important topic to learn about, in addition to the standard C input and output functions is file i/o.

A file is a place where a group of data is stored as a sequence of bytes for permanent storage of data. There are some functions for handling files such as create, open, close text, or binary files.

C includes certain functions to handle some file operations

NoFunctionsDescription
1.fopen()Creates a new or opens an existing file.
2.fclose()Closes a file
3.getc()Reads a character from a file.
4.putc()Writes a character to a file
5.fscanf()Reads a set of data from a file
6.fprintf()Writes a set of data to a file
7.getw()Reads an integer from a file
8.putw()Writes an integer to a file
9.fseek()Set the position to the desired point
10.ftell()Gives the current position of the file
11.rewind()Set the position to the beginning point

Opening a file

To create a new file or open an existing file we can use the fopen() function.

Syntax:

*fp=FILE*fopen(const char *filename, const char *mode)

*fp-file pointer

*filename-name of the file

*mode-Any of the different modes used for various purposes such as read, write, append, etc.

Mode
Text file
Mode
Binary file
Description
rrbOpens file in read mode
wwbOpens file in write mode
aabOpens file in append mode
r+rb+Opens file in read and write mode
w+wb+Opens file in read and write mode and
truncates the file to zero length
a+ab+Opens file in read and write mode,
read from the beginning
writing means just appending

Closing a file

We have fclose() to close the opened file.

Syntax:

int fclose(FILE *fp);

This function closes the file and releases the memory used for the file

It returns 0- Success

EOF-Error while closing a file

Writing a file

To write a character to a stream, we can use fputc() function

int fputc(int c, FILE *fp);

It returns the written character- success and

EOF- Error

To write a string to an output stream, we can use fputs() function.

We can use another function fprintf() to write a string to a file.

int fprintf(FILE *fp, const char *format, ...)

Reading a file:

To read a single character from a file we use fgetc() function,

int fgetc(FILE *fp);

It returns, the character read from a file on success and

EOF – when there is an error

The function fgets() is used for reading a string from a file.

char *fgets(char *buf, int n, FILE *fp)

It reads n-1 characters from the string until it finds a new line and includes null at the end of the string and returns all characters including the new line.

Another function we use to read string from a file is fscanf()

int fscanf(FILE *fp, const char *format)

It reads until it encounters a space character.

Binary File i/o

To read and write binary files we can use fread() and fwrite() functions.

It is mainly used to read and write blocks of memories such as arrays and structures.

fread()

size_t fread(void *buffer, size_t size, size_t count, FILE *stream )

Where

size_t -unsigned integer type

buffer – Storage location

count – number of items to be read

stream-pointer to file

The fread() function reads count value of mentioned size from the stream and stores it in the buffer.

It returns a total number of items read from the file on success and

the value less than count- when there is an error or end of the file.

fwrite()

size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream)

The fwrite() function writes total items of given count with each of given size from buffer to the file.

It returns all total items written to file on success and

value lesser than count- when there is an error or encounters the end of the file.

File Pointer Manipulation

In C we have functions such as ftell(), fseek() and rewind() for manipulating the file pointer indicator.

ftell()

long ftell(FILE *stream);

The ftell() returns the byte position of the pointer in a stream.

fseek()

We can modify the position indicator of the stream using fseek() function.

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

The new position can be calculated by adding offset to the position specified by whence

C defines three constants to move the position indicator, they are

SEEK_SET -First position

SEEK_CUR -Current position

SEEK_END -Final position

The fseek() and ftell() function helps to read the entire string even if the length is not known in advance.

rewind()

The rewind() function sets file position to the beginning of the file and clears errors and end of the file indicators for the stream.

void rewind(FILE *stream)

The rewind function does not return any value.

Recommended Articles

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *