0% found this document useful (0 votes)
6 views14 pages

Unit 5 1

The document provides an overview of file handling in C programming, including definitions, types of files, and functions for file operations. It details the syntax for opening files, reading and writing data, error handling, and the main function's arguments. Additionally, it includes examples of file I/O functions and a sample program for copying file content.

Uploaded by

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

Unit 5 1

The document provides an overview of file handling in C programming, including definitions, types of files, and functions for file operations. It details the syntax for opening files, reading and writing data, error handling, and the main function's arguments. Additionally, it includes examples of file I/O functions and a sample program for copying file content.

Uploaded by

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

UNIT-5-PPS

Q1)Define file?
A)In the C programming language, a file is a sequence of bytes
stored on a storage device,such as a hard drive, SSD, or any
other form of non-volatile memory. Files are used to store and
organize data in a structured manner. In C, file handling is done
using a set of standard library functions that provide a way to
interact with files.

Q2). Differentiate between text file and binary file?

A)

Q3)Differences between sequential file and random-access


file?

A)

Q4)Give syntax for opening a file?


A)In C, you can use the fopen() function to open a file. The
syntax for the fopen() function is as follows:
FILE *fopen(const char *filename, const char *mode);
Filename: The name of the file you want to open, including the
path if needed.
mode: A string specifying the mode in which the file should be
opened. The mode can include information about the
operations you intend to perform on the file, such as reading,
writing, or both.

Q5)Discuss modes of a file?


A)
1)Read Mode ("r"):
 Opens the file for reading.
 The file must exist; otherwise, fopen will return NULL.
 The file pointer is positioned at the beginning of the
file.
 SYNTAX:-
FILE *filePointer = fopen("[Link]", "r");

2)Write Mode ("w"):


 Opens the file for writing.
 If the file already exists, its contents are overwritten.
 If the file does not exist, a new file is created.
 The file pointer is positioned at the beginning of the
file.
 SYNTAX:-
FILE *filePointer = fopen("[Link]", "w");

3)Append Mode ("a"):


 Opens the file for appending.
 Data is written at the end of the file, preserving
existing content.
 If the file does not exist, a new file is created.
 The file pointer is positioned at the end of the file.
 SYNTAX:-
FILE *filePointer = fopen("[Link]", "a");

4)Read/Write Mode ("r+"):


 Opens the file for both reading and writing.
 The file must exist.
 The file pointer is positioned at the beginning of the
file.
 SYNTAX:-
FILE *filePointer = fopen("[Link]", "r+");

5)Write/Read Mode ("w+"):


 Opens the file for both reading and writing.
 If the file exists, its contents are overwritten.
 If the file does not exist, a new file is created.
 The file pointer is positioned at the beginning of the
file.
 SYNTAX:-
FILE *filePointer = fopen("[Link]", "w+");

6)Append/Read Mode ("a+"):


 Opens the file for reading and appending.
 Data can be read or written at the end of the file.
 If the file does not exist, a new file is created.
 The file pointer is positioned at the end of the file.
 SYNTAX:-
FILE *filePointer = fopen("[Link]", "a+");
Q6)Give syntax for fscanf and fprintf?
A)fscanf and fprintf are functions in C used for reading and
writing formatted data from and to files, respectively. Here are
their syntaxes:

fscanf Syntax:
int fscanf(FILE *stream, const char *format, ...);

fprintf Syntax:
int fprintf(FILE *stream, const char *format, ...);

stream: A pointer to the FILE structure that represents the file


to read from.
format: A string that specifies the format of the input. It may
contain format specifiers similar to printf.

Q7)Explain error handling file functions?


A)Error handling in file functions is crucial to ensure that your
program behaves correctly, especially when dealing with file
operations. When working with files in C, you should always
check for potential errors to handle cases such as file not found,
permission issues, or other unexpected situations.

1) Check File Pointers:When opening a file using fopen, check


if the returned file pointer is not NULL. If it is NULL, it
indicates that the file couldn't be opened
2) Check Return Values:After performing file operations like
reading or writing, check the return values of functions such
as fscanf, fprintf, fread, or fwrite. A return value less than
expected may indicate an issue.
3) Close Files Properly:Always close files using fclose when you
are done with them. Closing files is not just good practice; it
also helps release system resources.
4) Handle Errors Appropriately:Use meaningful error
messages to provide information about the nature of the
error. The perror function can be helpful for this purpose.
5) Graceful Program Termination:In case of severe errors,
consider terminating the program gracefully using
exit(EXIT_FAILURE) or other appropriate actions.

Q8)Give syntax for fread and fwrite?


A) The fread and fwrite functions in C are used for reading and
writing binary data from and to files, respectively. Here are
their syntaxes:

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

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

 ptr: A pointer to the data to be written to the file.


 size: The size, in bytes, of each element to be written.
 nmemb: The number of elements to be written.
 stream: A pointer to the FILE structure that represents the
file to write to.

Q9)Give syntax for fseek(). (most important )


A)The fseek() function in C is used to set the file position
indicator for a given file stream. It allows you to move the
position within a file, facilitating random access to different
parts of the file. The syntax for fseek() is as follows:

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

stream: A pointer to the FILE structure that represents the file.


offset: The number of bytes to move the file position indicator.
whence: Specifies the reference point for the offset. It can take
one of the following values:
SEEK_SET: The offset is from the beginning of the file.
SEEK_CUR: The offset is from the current file position.
SEEK_END: The offset is from the end of the file.

The function returns 0 on success and a non-zero value on


failure.

Q10)Explain the arguments used in main function?


A)The main function in C serves as the entry point for the
execution of a C program. It is a special function that the
operating system calls when the program is run. The main
function has the following general syntax:
SYNTAX:-int main(int argc, char *argv[])

int argc:
 argc stands for "argument count."
 It represents the number of command-line arguments
passed to the program, including the name of the program
itself.
 The minimum value of argc is 1.

char *argv[] or char **argv:


 argv stands for "argument vector."
 It is an array of strings (character pointers) representing the
command-line arguments.
 argv[0] contains the name of the program, and subsequent
elements (argv[1], argv[2], and so on) contain the actual
command-line arguments provided by the user.
 The last element of the array is always argv[argc], which is
set to NULL.
Long Answer Questions
Q1)Explain preprocessor directives.
A)Preprocessor directives in C are commands that are
processed by the C preprocessor before the actual compilation
of the code begins. They are lines in your code that begin with a
hash symbol (#). Preprocessor directives are not part of the C
language itself but provide instructions to the preprocessor,
which performs text manipulations before passing the code to
the compiler.
Here are some commonly used preprocessor directives:

1) #include:
 Used to include the contents of another file in your program.
 Syntax: #include <header_file> or #include "custom_file.h"
 Example:
#include <stdio.h>
#include "myheader.h"

2)#define:
 Used to define constants or macros.
 Syntax: #define identifier value
 Example:
#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))

3)#ifdef, #ifndef, #else, #endif:


 Used for conditional compilation.
 #ifdef: If defined.
 #ifndef: If not defined.
 #else: Otherwise.
 #endif: End of conditional block.
 Example:
#ifdef DEBUG
#else
#endif
4)#undef:
 Used to undefine a previously defined macro.
 Syntax: #undef identifier
 Example:
#define DEBUG
#undef DEBUG

5)#if, #elif, #else, #endif:


 Used for conditional compilation based on constant
expressions.
 Example:
#define VERSION 2
#if VERSION == 1
#elif
#else
#endif

6)#pragma:
 Used to provide additional information to the compiler.
 Syntax: #pragma directive
 Example:
#pragma once
// Equivalent to include guards, prevents multiple inclusion

 These directives help in code organization, conditional


compilation, and creating reusable and maintainable code.
They are processed by the C preprocessor, which performs
text substitutions before the actual compilation takes place.
Q2)Explain the file handling functions?
A)File handling functions in C are part of the standard
input/output library (<stdio.h>) and provide a way to read from
and write to files. These functions allow you to perform various
operations on files, such as opening, closing, reading, and
writing. Here are some key file handling functions in C:

fopen():
 Opens a file and returns a file pointer.
 Syntax: FILE *fopen(const char *filename, const char
*mode);
 Example:
FILE *filePointer = fopen("[Link]", "r");

fclose():
 Closes a file.
 Syntax: int fclose(FILE *stream);
 Example:
fclose(filePointer);

fprintf():
 Writes formatted data to a file.
 Syntax: int fprintf(FILE *stream, const char *format, ...);
 Example:
fprintf(filePointer, "This is a formatted string: %d", 42);

fscanf():
 Reads formatted data from a file.
 Syntax: int fscanf(FILE *stream, const char *format, ...);
 Example:
int value;fscanf(filePointer, "%d", &value);

fread():
 Reads a specified number of elements from a file.
 Syntax: size_t fread(void *ptr, size_t size, size_t nmemb,
FILE *stream);
 Example:
char buffer[100];
fread(buffer, sizeof(char), 100, filePointer);

fwrite():
 Writes a specified number of elements to a file.
 Syntax: size_t fwrite(const void *ptr, size_t size, size_t
nmemb, FILE *stream);
 Example:
char data[] = "Hello, World!";
fwrite(data, sizeof(char), sizeof(data) - 1, filePointer);

fseek():
 Sets the file position indicator.
 Syntax: int fseek(FILE *stream, long int offset, int whence);
 Example:
fseek(filePointer, 10, SEEK_SET); // Move to the 10th byte from
the beginning

ftell():
 Returns the current file position indicator.
 Syntax: long int ftell(FILE *stream);
 Example:
long int position = ftell(filePointer); // Get the current position

rewind():
 Resets the file position indicator to the beginning of the file.
 Syntax: void rewind(FILE *stream);
 Example:
rewind(filePointer); // Reset the file position to the beginning

feof():
 Checks for the end-of-file indicator.
 Syntax: int feof(FILE *stream);
 Example:
if (feof(filePointer)) {
// End of file reached}

These functions provide a comprehensive set of tools for


working with files in C. Always check for errors during file
operations and handle them appropriately to ensure robust file
handling in your programs

Q3)Write a c program to copy one file content to another and


display the copied file content?
A)
#include <stdio.h>

int main() {
FILE *sourceFile, *destinationFile;
char ch;
sourceFile = fopen("[Link]", "r");

if (sourceFile == NULL) {
perror("Error opening source file");
return 1; // Exit with an error code
}
destinationFile = fopen("[Link]", "w");

if (destinationFile == NULL) {
perror("Error opening destination file");
fclose(sourceFile);
return 1; // Exit with an error code
}

while ((ch = fgetc(sourceFile)) != EOF) {


fputc(ch, destinationFile);
}
fclose(sourceFile);
fclose(destinationFile);

destinationFile = fopen("[Link]", "r");

if (destinationFile == NULL) {
perror("Error opening destination file for reading");
return 1; // Exit with an error code
}

printf("Copied content:\n");

while ((ch = fgetc(destinationFile)) != EOF) {


putchar(ch);
}

fclose(destinationFile);

return 0;
}

Q4)FILE INPUT-OUTPUT FUNCTIONS.


A)
fprintf():
 Writes formatted data to a file.
 Syntax: int fprintf(FILE *stream, const char *format, ...);
 Example:
FILE*filePointer= fopen("[Link]", "w");fprintf(filePointer,
"This is a formatted string: %d", 42);
fclose(filePointer);
fscanf():
 Reads formatted data from a file.
 Syntax: int fscanf(FILE *stream, const char *format, ...);
 Example:
FILE *filePointer = fopen("[Link]", "r");int
value;fscanf(filePointer, "%d", &value);
fclose(filePointer);

fputs():
 Writes a string to a file.
 Syntax: int fputs(const char *str, FILE *stream);
 Example:
FILE *filePointer = fopen("[Link]", "w");fputs("This is a
string.", filePointer);
fclose(filePointer);

fgets():
 Reads a line from a file.
 Syntax: char *fgets(char *str, int size, FILE *stream);
 Example:
FILE *filePointer = fopen("[Link]", "r");char buffer[100];
fgets(buffer, sizeof(buffer), filePointer);
fclose(filePointer);

fputc():
 Writes a character to a file.
 Syntax: int fputc(int character, FILE *stream);
 Example:
FILE *filePointer = fopen("[Link]", "w");
fputc('A', filePointer);
fclose(filePointer);
fgetc():
 Reads a character from a file.
 Syntax: int fgetc(FILE *stream);
 Example:
FILE *filePointer = fopen("[Link]", "r");int character =
fgetc(filePointer);
fclose(filePointer);

These functions provide a variety of ways to perform input and


output operations on files in C. Always ensure proper error
checking and handling when working with files to make your
programs more robust and reliable.

You might also like