File Handling in C

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

File handling in C stores program data in volatile memory, which is lost upon program completion.

False (B)

In C, file handling involves storing data in a file using a program, but it does not support extracting data from files.

False (B)

Opening a file is not one of the fundamental operations that can be performed on a file in C.

False (B)

Binary files store data in ASCII characters, making them directly readable by humans.

<p>False (B)</p> Signup and view all the answers

Text files in C are primarily saved with a .doc extension for compatibility with word processing software.

<p>False (B)</p> Signup and view all the answers

Binary files take more storage space than text files because they store data in a more complex format.

<p>False (B)</p> Signup and view all the answers

The fopen() function is exclusively used for creating new files and cannot open existing files.

<p>False (B)</p> Signup and view all the answers

The fputc() function is used to write strings to a file.

<p>False (B)</p> Signup and view all the answers

The fseek() function can move the file pointer to the end of the file, but not to the beginning or current position.

<p>False (B)</p> Signup and view all the answers

The ftell() function returns the current position of the file pointer in the file.

<p>True (A)</p> Signup and view all the answers

The rewind() function sets the file pointer to the end of the file.

<p>False (B)</p> Signup and view all the answers

Using the "r+" mode with fopen() allows reading, but not writing, to a text file.

<p>False (B)</p> Signup and view all the answers

When opening a file in write mode ("w"), the existing content of the file, if any, is preserved.

<p>False (B)</p> Signup and view all the answers

The stdio.h header file is not required to use file handling functions.

<p>False (B)</p> Signup and view all the answers

Pre-processor directives are processed by the compiler after the source code is compiled.

<p>False (B)</p> Signup and view all the answers

All pre-processor directives in C begin with a dollar $ symbol.

<p>False (B)</p> Signup and view all the answers

The #include directive only provides a command to the preprocessor and does not include code by itself.

<p>False (B)</p> Signup and view all the answers

The #undef preprocessor directive is used to define a new macro.

<p>False (B)</p> Signup and view all the answers

Macros in C are directly executed at runtime.

<p>False (B)</p> Signup and view all the answers

Macros can only be used to define constant values and cannot include code segments.

<p>False (B)</p> Signup and view all the answers

Bitwise operators are used to perform arithmetic calculations on integer values.

<p>False (B)</p> Signup and view all the answers

The bitwise AND operator (&) returns 1 only if both corresponding bits are 1, otherwise it returns 0.

<p>True (A)</p> Signup and view all the answers

The bitwise OR operator (|) returns 0 only when both corresponding bits are 0.

<p>True (A)</p> Signup and view all the answers

The bitwise XOR operator (^) returns 1 if the corresponding bits are the same (both 0 or both 1).

<p>False (B)</p> Signup and view all the answers

The bitwise complement operator (~) flips all the bits in a value, changing 0s to 1s and 1s to 0s.

<p>True (A)</p> Signup and view all the answers

Flashcards

File Handling

Storing data in a file using a program.

Text file

A file storing data as ASCII characters, readable by humans.

Binary file

A file storing data in binary format (0s and 1s).

fopen()

Opens a file for reading or creation.

Signup and view all the flashcards

fprintf()

Writes formatted data to a file.

Signup and view all the flashcards

fscanf()

Reads formatted data from a file.

Signup and view all the flashcards

fputc()

Writes a character to a file.

Signup and view all the flashcards

fgetc()

Reads a character from a file.

Signup and view all the flashcards

fclose()

Closes an open file.

Signup and view all the flashcards

fseek()

Repositions the file pointer to a specific location.

Signup and view all the flashcards

ftell()

Returns the current position of a file pointer.

Signup and view all the flashcards

rewind()

Sets the file pointer to the beginning of a file.

Signup and view all the flashcards

fwrite()

Writes blocks of data to a file.

Signup and view all the flashcards

fread()

Reads blocks of data from a file.

Signup and view all the flashcards

Pre-processor

Processes source code before compilation.

Signup and view all the flashcards

#define

Substitutes a preprocessor macro.

Signup and view all the flashcards

#include

Inserts a header file into a source file.

Signup and view all the flashcards

#undef

Undefines a preprocessor macro.

Signup and view all the flashcards

#ifdef

Conditional compilation based on macro existence.

Signup and view all the flashcards

#ifndef

Returns true if this macro is not defined.

Signup and view all the flashcards

#if

Tests if a compile-time condition is true.

Signup and view all the flashcards

#else

Alternative for #if.

Signup and view all the flashcards

#error

Prints an error message during compilation.

Signup and view all the flashcards

Bitwise Operators

Manipulate individual bits.

Signup and view all the flashcards

& (Bitwise AND)

Bitwise AND operation

Signup and view all the flashcards

Study Notes

File Handling in C

  • Stores program data to local storage for later use

  • Addresses data loss upon program completion by saving to files

  • File handling involves storing program data in files

  • Programs can store results and extract data for use within C

  • Operations Performable on Files:

    • Create new file
    • Open existing file
    • Read data from existing file
    • Write data to a file
    • Move data within a file
    • Close a file

Types of Files

  • Text files:
    • User-creatable
    • Readable
    • Use ASCII
    • Editable using a text editor
    • Use TXT or RTF extensions
  • Binary files:
    • Stores 0s and 1s
    • Saves space
    • Use BIN extension
    • Not human-readable
    • More space efficient

File Handling Functions in C

  • fopen(): Opens new or existing file, requires filename and mode
  • fprintf(): Writes formatted data to a file, requires stream, format, and optional arguments
  • fscanf(): Reads formatted data from a file, requires stream, format, and optional arguments
  • fputc(): Writes a character to a file, requires character and stream
  • fgetc(): Reads a character from a file, requires stream
  • fclose(): Closes a file, requires file pointer
  • fseek(): Sets file pointer to specific position, requires stream, offset, and origin
  • fputw(): Writes an integer value to a file, requires integer and file pointer
  • fgetw(): Reads an integer value from a file, requires file pointer
  • ftell(): Returns the current position of the file pointer, requires stream
  • rewind(): Sets the file pointer to the beginning of the file, requires stream

File Opening Modes with fopen()

  • "r": Opens text file for reading only
  • "w": Opens text file for writing only, deleting existing content
  • "a": Opens text file for appending
  • "r+": Opens text file for both reading and writing
  • "w+": Opens text file for both reading and writing, deleting existing content
  • "a+": Opens text file for both reading and writing in append mode
  • "rb": Opens binary file for reading
  • "wb": Opens binary file for writing
  • "ab": Opens binary file for appending
  • "rb+": Opens binary file for both reading and writing
  • "wb+": Opens binary file for both reading and writing, deleting existing content
  • "ab+": Opens binary file for both reading and writing in append mode
  • Append mode adds data without deleting; write mode overwrites existing data

Creating Files

  • fopen() creates new files

  • Syntax: fopen("filename", "mode")

  • The FILE pointer type references files

  • fopen() returns the file address to the file pointer

  • Example: Creating "BCA.txt"

#include <stdio.h>
int main() {
  FILE *file;
  file = fopen("BCA.txt", "w");
}
  • Files are created in the code's folder
  • Write mode creates a new file if one is absent

Opening Files

  • fopen() opens files with specified modes
#include <stdio.h>
int main() {
  FILE *file;
  file = fopen("BCA.txt","r");
}

Writing to Files

  • fprintf() writes to files
#include <stdio.h>
int main() {
  FILE *file;
  file = fopen("BCA.txt", "w");
  fprintf(file, "Hello! Welcome to BCA SEM-2 MJCC.\n");
}

Reading from Files

  • "r" mode opens files for reading
  • getc() reads files character by character
  • fgets() reads files line by line
#include <stdio.h>
#include <stdlib.h>
int main() {
  FILE *fp;
  char s;
  fp=fopen("BCA.txt","r");
  if(fp==NULL) {
    printf("\nCAN NOT OPEN FILE");
    exit(1);
  }
  do {
    s=getc(fp); // read file character by character
    printf("%c",s);
  } while(s!=EOF);
  fclose(fp);
  return 0;
}

Moving Data within a file

  • fseek() repositions the file pointer

  • Allows writing to specific file locations

  • fseek() is in stdio.h

  • Shifts file pointer used to read the file, to a specified offset position

  • fseek() syntax: fseek(FILE *filePointer, long offset, int origin);

    • filePointer: modifies stream
    • offset: bytes to shift FILE pointer relative to current origin
    • origin: current FILE pointer position to add offset
    • SEEK_END: end of file
    • SEEK_SET: start of the file
    • SEEK_CUR: current position of the file pointer
#include <stdio.h>
void main() {
  FILE *fp;
  fp = fopen("test.txt", "r");
  fseek(fp, 0, SEEK_END); // Moving pointer to end
  printf("%ld", ftell(fp)); // Printing position of pointer
  getch();
}

Fwrite and Fread

  • fprintf and putc write strings/integers

  • fwrite and fread are useful to read and display data in blocks

  • fwrite declaration: size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

    • ptr: pointer to array of elements to be written
    • size: bytes per element
    • nmemb: number of elements
    • stream: pointer to a FILE object that specifies an output stream
  • fread declaration: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

    • ptr: pointer to a block of memory
    • size: bytes per element
    • nmemb: number of elements
    • stream: pointer to a FILE object that specifies an input stream

Closing files

  • fclose() closes open files
#include <stdio.h>
int main(){
  FILE *file;
  file = fopen("BCA.txt", "w");
  fprintf(file, "Hello! Welcome to BCA SEM-2 MJCC.\n");
  fclose(file);
}
  • This releases the file pointer

Preprocessors

  • Preprocessors alter codes before compiling

  • Preprocessor directives begin with #

  • # indicates preprocessor execution

  • Examples of preprocessor directives: #include, #define, #ifndef

  • # directs to the preprocessor and the preprocessor deals with commands like include

  • Directives can be placed anywhere in programs

  • Preprocessor directives:

    • #define: macro substitution
    • #include: inserts headers
    • #undef: undefines macros
    • #ifdef: conditional if macro is defined
    • #ifndef: conditional if macro is not defined
    • #if: compile-time condition
    • #else: alternative for #if
    • #elif: else and if
    • #endif: ends conditional
    • #error: prints error
    • #pragma: issues compiler commands

Macros

  • Macros are defined with #define

  • They allow code replacement with a single value

  • Macros enable scalable code

  • Typical Macro structure:

    • Directive
    • Name
    • Value
#include <stdio.h>
// This is macro definition
#define PI 3.14
void main() {
    // declaration and initialization of radius
    int radius = 5;
    // declaration and calculating the area
    float area = PI * (radius*radius);
    // Printing the area of circle
    printf("Area of circle is %f", area);
}

Bitwise Operators in C

  • Manipulates bits using bitwise operators (|, &, ^, <<, >>, ~)
    AND (&)
    OR (|)
    XOR (^)
    COMPLEMENT (~)
    Left Shift (<<)
    Right Shift (>>)
  • These operators produce different results than logical operators

AND

  • The bitwise AND operator (&) is a binary operator
  • It requires two integer operands
  • Num1 & Num2
  • If both bits are 1, the result is 1; otherwise, it is 0
  • Truth Table: Num1| Num2| Result
  • ----|------|------- 0|0| 0 1|0| 0 0|1| 0 1|1| 1
int ans, num1 = 3, num2 = 4;
ans = num1 & num2;
printf("3 & 4 = %d", ans);
//output
3&4=0
  • Example notes:
    • Convert to binary, adding leading zeros as appropriate
    • Evaluate each position using bitwise AND
    • The given code snippet performs the bitwise AND operation on 3 and 4.
    • The binary value for 3 is 11 and 4 is 100.
    • First, we have to convert the shortest binary value to the length of the longest one, by
    • adding zeros to the left side - the most significant bit.
    • Here the number with the shortest length is 3, with lengths 2 and the largest one is 4
    • with length 3. Convert them to the same length by adding 0s as the most significant bit
    • in 3.
    • So, now we have 011 as binary representations for 3 and 100 for 4.
    • Now move from left to right, and perform logical AND operations on the bits and store
    • the result in the corresponding position.
    • The first bit of 3 is 0 and the first bit of 4 is 1, the logical AND will consider 0 as False
    • and 1 as True, so the result will be false and 0 will be the first bit of the result.
    • The same process repeats itself throughout the length of the binary values. The
    • second bit of 3 and 4 are 0 and 0 respectively, so again 0 will be stored as the second
    • bit of the result.
    • The third and last bit of both 3 and 4 are 0 and 0, so again 0 will be the third and final
    • bit of our result.
    • So the final binary value of our result will be 000, which when converted to integer
    • decimal results to 0.

OR

  • The bitwise OR operator (|) is a binary operator
  • It requires two integer operands
  • If at least one of the bits has 1, then output has 1, otherwise 0.
  • Truth Table: Num1| Num2| Result
  • ----|------|------- 0|0| 0 1|0| 1 0|1| 1 1|1| 1
int ans, num1 = 3, num2 = 4;
ans = num1 | num2;
printf("3 | 4 = %d", ans);
//output
3|4=7
  • Example Notes include the below
    • The above code snippet performs the bitwise OR operation on 3
    • and 4. Let’s see their working in detail.
    • The binary value for 3 is 11 and 4 is 100.
    • First, we have to convert the shortest binary value to the length of
    • the longest one, by adding zeros to the left side - the most
    • significant bit.
    • So, now we have 011 for 3 and 100 for 4.
    • Now move from left to right, and perform logical OR operations on
    • the bits and store the result in the corresponding position
    • The first bit of both 3 and 4 are 0 and 1, respectively, so the first bit
    • of the result is 1.
    • The second bit of both 3 and 4 are 1 and 0, respectively, so the
    • second bit of the result is also 1.
    • The third bit of both 3 and 4 are 1 and 0, respectively, so the third
    • bit of the result is also 1.
    • So the binary value of the result is 111, which when you convert
    • from binary to decimal returns 7.

XOR

  • The bitwise XOR operator (^) is a binary operator
  • It performs if exactly one of the bits is 1 (0 otherwise)
  • Truth Table:

Num1| Num2| Result

  • ----|------|------- 0|0| 0 1|0| 1 0|1| 1 1|1| 0
int ans, num1 = 3, num2 = 4;
ans = num1 ^ num2;
printf("3 ^ 4 = %d", ans);
//output
3^4=7

Complement

  • The bitwise complement operator (~) is an unary operator
  • It requires one integer operands.
  • It changes 0s in bits to 1s and vice versa
  • Truth Table: Num1| Result
  • ----|------- 0|1 1|0
int ans, num1 = 5;
ans = ~num1;
printf("~5 = %d", ans);
//output
~5 = 6

Shift Left

  • The shift left operator (<<) is a binary operator

  • It shifts bits to the left

  • Syntax: ans = x << n;

  • Value of x can be negative, but n cannot, or you throw an error message

  • If x is negative it is performed on the two's complement.

int ans, num1 = 5;
ans = num1 << 2;
printf("5 << 2 = %d", ans);
//output
5 << 2 = 20

Shift Right

  • The shift right operator (>>) is a binary operator
  • It shifts bits to the right
  • Syntax: ans = x >> n;
int ans, num1 = 20;
ans = num1 >> 2;
printf("20 >> 2 = %d", ans);
//output
20 >> 2 = 5

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Python File Handling Quiz
9 questions
C# Programming: Data Types and File Handling
12 questions
File Handling in C Programming
15 questions
Use Quizgecko on...
Browser
Browser