0% found this document useful (0 votes)
19 views25 pages

4th Unit

notes

Uploaded by

vtilokani1981
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views25 pages

4th Unit

notes

Uploaded by

vtilokani1981
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Arrays:

Array in C is one of the most used data structures in C programming. It is a simple and fast
way of storing multiple values under a single name. In this article, we will study the different
aspects of array in C language such as array declaration, definition, initialization, types of
arrays, array syntax, advantages and disadvantages, and many more.

What is Array in C?

An array in C is a fixed-size collection of similar data items stored in contiguous memory


locations. It can be used to store the collection of primitive data types such as int, char, float,
etc., and also derived and user-defined data types such as pointers, structures, etc.

C Array Declaration

In C, we have to declare the array like any other variable before using it. We can declare an
array by specifying its name, the type of its elements, and the size of its dimensions. When we
declare an array in C, the compiler allocates the memory block of the specified size to the array
name.

Syntax of Array Declaration

data_type array_name [size];

or

data_type array_name [size1] [size2]...[sizeN];

Example of Array Declaration

// C Program to illustrate the array declaration

#include <stdio.h>

int main()
{

// declaring array of integers


int arr_int[5];
// declaring array of characters
char arr_char[5];

return 0;
}
C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is
declared or allocated memory, the elements of the array contain some garbage value. So, we
need to initialize the array to some meaningful value. There are multiple ways in which we can
initialize an array in C.

1. Array Initialization with Declaration


In this method, we initialize the array along with its declaration. We use an initializer list to
initialize multiple elements of the array. An initializer list is the list of values enclosed within
braces { } separated b a comma.

data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size


If we initialize an array using an initializer list, we can skip declaring the size of the array as
the compiler can automatically deduce the size of the array in these cases. The size of the array
in these cases is equal to the number of elements present in the initializer list as the compiler
can automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};
The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)


We initialize the array after the declaration by assigning the initial value to each element
individually. We can use for loop, while loop, or do-while loop to assign the value to each
element of the array.
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Example of Array Initialization in C
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
// array initialization using initialier list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0;
}
Access Array Elements
We can access any element of an array in C using the array subscript operator [ ] and the index
value i of the element.

array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first element is
at index 0 and the last element is at N – 1 where N is the number of elements in the array.
Example of Accessing Array Elements using Array Subscript Operator

// C Program to illustrate element access using array


// subscript
#include <stdio.h>

int main()
{

// array declaration and initialization


int arr[5] = { 15, 25, 35, 45, 55 };

// accessing element at index 2 i.e 3rd element


printf("Element at arr[2]: %d\n", arr[2]);

// accessing element at index 4 i.e last element


printf("Element at arr[4]: %d\n", arr[4]);

// accessing element at index 0 i.e first element


printf("Element at arr[0]: %d", arr[0]);

return 0;
}

Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as follows:

One Dimensional Arrays (1D Array)


Multidimensional Arrays

1. One Dimensional Array in C


The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.

Syntax of 1D Array in C
array_name [size];
Example of 1D Array in C

// C Program to illustrate the use of 1D array


#include <stdio.h>

int main()
{
// 1d array declaration
int arr[5];

// 1d array initialization using for loop


for (int i = 0; i < 5; i++) {
arr[i] = i * i - 2 * i + 1;
}
printf("Elements of Array: ");
// printing 1d array by traversing using for loop
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of
the popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with
more dimensions than 3d arrays but they are avoided as they get very complex and occupy a
large amount of space.

A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They
can be visualized in the form of rows and columns organized in a two-dimensional plane.

Syntax of 2D Array in C
array_name[size1] [size2];

Here,

size1: Size of the first dimension.


size2: Size of the second dimension.

Example of 2D Array in C

// C Program to illustrate 2d array


#include <stdio.h>

int main()
{
// declaring and initializing 2d array
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}

Passing an Array to a Function in C


An array is always passed as pointers to a function in C. Whenever we try to pass an array to a
function, it decays to the pointer and then passed as a pointer to the first element of an array.

We can verify this using the following C Program:


// C Program to pass an array to a function
#include <stdio.h>
void printArray(int arr[])
{
printf("Size of Array in Functions: %d\n", sizeof(arr));
printf("Array Elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ",arr[i]);
}
}

// driver code
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
printf("Size of Array in main(): %d\n", sizeof(arr));
printArray(arr);
return 0;

Advantages of Array in C

The following are the main advantages of an array:

 Random and fast access of elements using the array index.


 Use of fewer lines of code as it creates a single array of multiple elements.
 Traversal through the array becomes easy using a single loop.
 Sorting becomes easy as it can be accomplished by writing fewer lines of code.
 Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
 Insertion and deletion of elements can be costly since the elements are needed to be
rearranged after insertion and deletion.

C Structures:

The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of any
valid data type.

C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to
declare the structure in C using the following syntax:
Syntax

struct structure_name {

data_type member_name1;

data_type member_name1;

....

....
};

The above syntax is also called a structure template or structure prototype and no memory is
allocated to the structure in the declaration.

C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:
1. Structure Variable Declaration with Structure Template
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template


// structure declared beforehand
struct structure_name variable1, variable2, .......;
Access Structure Members
We can access structure members by using the ( . ) dot operator.
Syntax
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to
access the members.
Nested Structures

C language allows us to insert one structure into another as a member. This process is called
nesting and such structures are called nested structures. There are two ways in which we can
nest one structure into another:

1. Embedded Structure Nesting

In this method, the structure being nested is also declared inside the parent structure.
Example
struct parent {
int member1;

struct member_str member2 {

int member_str1;

char member_str2;

...

...

2. Separate Structure Nesting

In this method, two structures are declared separately and then the member structure is nested
inside the parent structure.
Example

struct member_str {

int member_str1;
char member_str2;
...
}
struct parent {
int member1;

struct member_str member2;

...

One thing to note here is that the declaration of the structure should always be present before
its definition as a structure member. For example, the declaration below is invalid as the struct
mem is not defined when it is declared inside the parent structure.

struct parent {

struct mem a;

};

struct mem {

int var;

};

Accessing Nested Members

We can access nested Members by using the same ( . ) dot operator two times as shown:

str_parent.str_child.member;

Example of Structure Nesting

// C Program to illustrate structure nesting along with

// forward declaration

#include <stdio.h>

// child structure declaration

struct child {
int x;
char c;
};

// parent structure declaration

struct parent {
int a;
struct child b;
};
// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };
// accessing and printing nested members
printf("var1.a = %d\n", var1.a);
printf("var1.b.x = %d\n", var1.b.x);
printf("var1.b.c = %c", var1.b.c);

return 0;

Uses of Structure in C

C structures are used for the following:


 The structure can be used to define the custom data types that can be used to create
some complex data types such as dates, time, complex numbers, etc. which are not
present in the language.
 It can also be used in data organization where a large amount of data can be stored in
different fields.
 Structures are used to create data structures such as trees, linked lists, etc.
 They can also be used for returning multiple values from a function.

Limitations of C Structures
In C language, structures provide a method for packing together data of different types. A
Structure is a helpful tool to handle a group of logically related data items. However, C
structures also have some limitations.

 Higher Memory Consumption: It is due to structure padding.


 No Data Hiding: C Structures do not permit data hiding. Structure members can be
accessed by any function, anywhere in the scope of the structure.
 Functions inside Structure: C structures do not permit functions inside the structure so
we cannot provide the associated functions.
 Static Members: C Structure cannot have static members inside its body.
 Construction creation in Structure: Structures in C cannot have a constructor inside
Structures.
Basics of File Handling in C:

File handing in C is the process in which we create, open, read, write, and close operations on a
file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(),
etc. to perform input, output, and many different C file operations in our program.

Why do we need File Handling in C?

So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. The output is deleted when the program is closed. But in the software industry, most
programs are written to store the information fetched from the program. The use of file
handling is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few features of using
files:
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and
anytime providing high reusability.

Portability: Without losing any data, files can be transferred to another in the computer system.
The risk of flawed coding is minimized with this feature.

Efficient: A large amount of input may be required for some programs. File handling allows
you to easily access a part of a file using few instructions which saves a lot of time and reduces
the chance of errors.

Storage Capacity: Files allow you to store a large amount of data without having to worry
about storing everything simultaneously in a program.

Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as
follows:

 Text Files

 Binary Files

1. Text Files

A text file contains data in the form of ASCII characters and is generally used to store a stream
of characters.

 Each line in a text file ends with a new line character (‘\n’).
 It can be read or written by any text editor.
 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.

2. Binary Files

A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.The
binary files can be created only from within a program and their contents can only be read by a
program.

 More secure as they are not easily readable.


 They are generally stored with .bin file extension.

C File Operations

C file operations refer to the different possible operations that we can perform on a file in C
such as:

 Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
 Opening an existing file – fopen()
 Reading from file – fscanf() or fgets()
 Writing to a file – fprintf() or fputs()
 Moving to a specific location in a file – fseek(), rewind()
 Closing a file – fclose()

Open a File in C

For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.

Syntax of fopen()

FILE* fopen(const char *file_name, const char *access_mode);

Parameters

 file_name: name of the file when present in the same directory as the source file.
Otherwise, full path.

 access_mode: Specifies for what operation the file is being opened.

Return Value
 If the file is opened successfully, returns a file pointer to it.

 If the file is not opened, then returns NULL.

File opening modes in C

File opening modes or access modes specify the allowed operations on the file to be opened.
They are passed as an argument to the fopen() function. Some of the commonly used file
access modes are listed below:

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
r a pointer that points to the first character in it. If the file cannot be opened fopen( )
returns NULL.

rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.

Open for writing in text mode. If the file exists, its contents are overwritten. If the file
w
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

Open for writing in binary mode. If the file exists, its contents are overwritten. If the file
wb
does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a a pointer that points to the last character in it. It opens only in the append mode. If the
file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the file. If the file does not
ab
exist, it will be created.

Searches file. It is opened successfully fopen( ) loads it into memory and sets up a
r+
pointer that points to the first character in it. Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file does not exist, fopen( )
rb+
returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new
w+
file is created. Returns NULL, if unable to open the file.

wb+ Open for both reading and writing in binary mode. If the file exists, its contents are
Opening
Modes Description

overwritten. If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a pointer that points to the last character in it. It opens the file in both reading and append
a+
mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the
file.

Open for both reading and appending in binary mode. If the file does not exist, it will be
ab+
created.

As given above, if you want to perform operations on a binary file, then you have to append ‘b’
at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use
“a+b”.

Example of Opening a File

 C

// C Program to illustrate file opening

#include <stdio.h>

#include <stdlib.h>

int main()

// file pointer variable to store the value returned by

// fopen

FILE* fptr;

// opening the file in read mode

fptr = fopen("filename.txt", "r");

// checking if the file is opened successfully

if (fptr == NULL) {

printf("The file is not opened. The program will "


"now exit.");

exit(0);

return 0;

Output

The file is not opened. The program will now exit.

The file is not opened because it does not exist in the source directory. But the fopen() function
is also capable of creating a file if it does not exist. It is shown below

Create a File in C

The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found such as
w, w+, wb, wb+, a, a+, ab, and ab+.

FILE *fptr;
fptr = fopen("filename.txt", "w");

Example of Opening a File

 C

// C Program to create a file

#include <stdio.h>

#include <stdlib.h>

int main()

// file pointer

FILE* fptr;

// creating file using fopen() access mode "w"

fptr = fopen("file.txt", "w");

// checking if the file is created


if (fptr == NULL) {

printf("The file is not opened. The program will "

"exit now");

exit(0);

else {

printf("The file is created Successfully.");

return 0;

Output

The file is created Successfully.

Reading From a File

The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file. Such
functions are listed below:

Function Description

fscanf() Use formatted string and variable arguments list to take input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

So, it depends on you if you want to read the file line by line or character by character.

Example:

FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);

The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.

Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.

Write to a File

The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can be
used to write data to a file such as:

Function Description

fprintf( Similar to printf(), this function use formatted string and varible arguments list to print
) output to the file.

fputs() Prints the whole line in the file and a newline at the end.

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

fwrite() This functions write the specified amount of bytes to the binary file.

Example:

FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);

Closing a File

The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.

Syntax of fclose()

fclose(file_pointer);

where the file_pointer is the pointer to the opened file.

Example:

FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);

Examples of File Handing in C

Example 1: Program to Create a File, Write in it, And Close the File

 C

// C program to Open a File,

// Write in it, And Close the File

#include <stdio.h>

#include <string.h>

int main()

// Declare the file pointer

FILE* filePointer;

// Get the data to be written in file

char dataToBeWritten[50] = "GeeksforGeeks-A Computer "

"Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()

// in write mode using "w" attribute

filePointer = fopen("GfgTest.c", "w");

// Check if this filePointer is null

// which maybe if the file does not exist

if (filePointer == NULL) {

printf("GfgTest.c file failed to open.");

else {
printf("The file is now opened.\n");

// Write the dataToBeWritten into the file

if (strlen(dataToBeWritten) > 0) {

// writing in the file using fputs()

fputs(dataToBeWritten, filePointer);

fputs("\n", filePointer);

// Closing the file using fclose()

fclose(filePointer);

printf("Data successfully written in file "

"GfgTest.c\n");

printf("The file is now closed.");

return 0;

Output

The file is now opened.

Data successfully written in file GfgTest.c

The file is now closed.

This program will create a file named GfgTest.c in the same directory as the source file which
will contain the following text: “GeeksforGeeks-A Computer Science Portal for Geeks”.

Example 2: Program to Open a File, Read from it, And Close the File

 C

// C program to Open a File,

// Read from it, And Close the File


#include <stdio.h>

#include <string.h>

int main()

// Declare the file pointer

FILE* filePointer;

// Declare the variable for the data to be read from

// file

char dataToBeRead[50];

// Open the existing file GfgTest.c using fopen()

// in read mode using "r" attribute

filePointer = fopen("GfgTest.c", "r");

// Check if this filePointer is null

// which maybe if the file does not exist

if (filePointer == NULL) {

printf("GfgTest.c file failed to open.");

else {

printf("The file is now opened.\n");

// Read the dataToBeRead from the file

// using fgets() method

while (fgets(dataToBeRead, 50, filePointer)

!= NULL) {
// Print the dataToBeRead

printf("%s", dataToBeRead);

// Closing the file using fclose()

fclose(filePointer);

printf(

"Data successfully read from file GfgTest.c\n");

printf("The file is now closed.");

return 0;

Output

The file is now opened.


GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.

This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.

Read and Write in a Binary File

Till now, we have only discussed text file operations. The operations on a binary file are
similar to text file operations with little difference.

Opening a Binary File

To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in the
fopen() function. We also use the .bin file extension in the binary filename.

Example

fptr = fopen("filename.bin", "rb");

Write to a Binary File

We use fwrite() function to write data to a binary file. The data is written to the binary file in
the from of bits (0’s and 1’s).

Syntax of fwrite()

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

Parameters:
 ptr: pointer to the block of memory to be written.

 size: size of each element to be written (in bytes).

 nmemb: number of elements.

 file_pointer: FILE pointer to the output file stream.

Return Value:

 Number of objects written.

Example: Program to write to a Binary file using fwrite()

 C

// C program to write to a Binary file using fwrite()

#include <stdio.h>

#include <stdlib.h>

struct threeNum {

int n1, n2, n3;

};

int main()

int n;

// Structure variable declared here.

struct threeNum num;

FILE* fptr;

if ((fptr = fopen("C:\\program.bin", "wb")) == NULL) {

printf("Error! opening file");

// If file pointer will return NULL

// Program will exit.

exit(1);

int flag = 0;

// else it will return a pointer to the file.

for (n = 1; n < 5; ++n) {

num.n1 = n;

num.n2 = 5 * n;
num.n3 = 5 * n + 1;

flag = fwrite(&num, sizeof(struct threeNum), 1,

fptr);

// checking if the data is written

if (!flag) {

printf("Write Operation Failure");

else {

printf("Write Operation Successful");

fclose(fptr);

return 0;

Output

Write Operation Successful

Reading from Binary File

The fread() function can be used to read data from a binary file in C. The data is read from the
file in the same form as it is stored i.e. binary form.

Syntax of fread()

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

Parameters:

 ptr: pointer to the block of memory to read.

 size: the size of each element to read(in bytes).

 nmemb: number of elements.

 file_pointer: FILE pointer to the input file stream.

Return Value:

 Number of objects written.

Example: Program to Read from a binary file using fread()


 C

// C Program to Read from a binary file using fread()

#include <stdio.h>

#include <stdlib.h>

struct threeNum {

int n1, n2, n3;

};

int main()

int n;

struct threeNum num;

FILE* fptr;

if ((fptr = fopen("C:\\program.bin", "rb")) == NULL) {

printf("Error! opening file");

// If file pointer will return NULL

// Program will exit.

exit(1);

// else it will return a pointer to the file.

for (n = 1; n < 5; ++n) {

fread(&num, sizeof(struct threeNum), 1, fptr);

printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2,

num.n3);

fclose(fptr);

return 0;

Output

n1: 1 n2: 5 n3: 6


n1: 2 n2: 10 n3: 11
n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21

fseek() in C

If we have multiple records inside a file and need to access a particular record that is at a
specific position, so we need to loop through all the records before it to get the record. Doing
this will waste a lot of memory and operational time. To reduce memory consumption and
operational time we can use fseek() which provides an easier way to get to the required data.
fseek() function in C seeks the cursor to the given record in the file.

Syntax for fseek()

int fseek(FILE *ptr, long int offset, int pos);

Example of fseek()

 C

// C Program to demonstrate the use of fseek() in C

#include <stdio.h>

int main()

FILE* fp;

fp = fopen("test.txt", "r");

// Moving pointer to end

fseek(fp, 0, SEEK_END);

// Printing position of pointer

printf("%ld", ftell(fp));

return 0;

Output

81

rewind() in C

The rewind() function is used to bring the file pointer to the beginning of the file. It can be
used in place of fseek() when you want the file pointer at the start.
Syntax of rewind()

rewind (file_pointer);

Example

 C

// C program to illustrate the use of rewind

#include <stdio.h>

int main()

FILE* fptr;

fptr = fopen("file.txt", "w+");

fprintf(fptr, "Geeks for Geeks\n");

// using rewind()

rewind(fptr);

// reading from file

char buf[50];

fscanf(fptr, "%[^\n]s", buf);

printf("%s", buf);

return 0;

Output

Geeks for Geeks

More Functions for C File Operations

The following table lists some more functions that can be used to perform file operations or
assist in performing them.
Functions Description

fopen() It is used to create a file or to open a file.

fclose() It is used to close a file.

fgets() It is used to read a file.

fprintf() It is used to write blocks of data into a file.

fscanf() It is used to read blocks of data from a file.

getc() It is used to read a single character to a file.

putc() It is used to write a single character to a file.

fseek() It is used to set the position of a file pointer to a mentioned location.

ftell() It is used to return the current position of a file pointer.

rewind() It is used to set the file pointer to the beginning of a file.

putw() It is used to write an integer to a file.

getw() It is used to read an integer from a file.

You might also like