The Wayback Machine - https://web.archive.org/web/20241006044551/https://www.geeksforgeeks.org/c-program-to-read-a-range-of-bytes-from-file-and-print-it-to-console/
Open In App

C program to read a range of bytes from file and print it to console

Last Updated : 28 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console.

Functions Used:

  1. fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.
  2. fgetc(): Reading the characters from the file.
  3. fclose(): For closing a file.

Approach:

  • Initialize a file pointer, say File *fptr1.
  • Initialize an array to store the bytes that will be read from the file.
  • Open the file using the function fopen() as fptr1 = fopen(argv[1], “r”).
  • Iterate a loop until the given file is read and stored, the characters are scanned in the variable, say C using the fgetc() function.
  • Store each character C extracted in the above step, to a new string S and print that string using the printf() function.
  • After completing the above steps, close the file using the fclose() function.

Below is the implementation of the above approach:

C




// C program to read particular bytes
// from the existing file
#include <stdio.h>
#include <stdlib.h>
  
// Maximum range of bytes
#define MAX 1000
  
// Filename given as the command
// line argument
int main(int argc, char* argv[])
{
    // Pointer to the file to be
    // read from
    FILE* fptr1;
    char c;
  
    // Stores the bytes to read
    char str[MAX];
    int i = 0, j, from, to;
  
    // If the file exists and has
    // read permission
    fptr1 = fopen(argv[1], "r");
  
    if (fptr1 == NULL) {
        return 1;
    }
  
    // Input from the user range of
    // bytes inclusive of from and to
    printf("Read bytes from: ");
    scanf("%d", &from;);
    printf("Read bytes upto: ");
    scanf("%d", &to;);
  
    // Loop to read required byte
    // of file
    for (i = 0, j = 0; i <= to
                       && c != EOF;
         i++) {
  
        // Skip the bytes not required
        if (i >= from) {
            str[j] = c;
            j++;
        }
  
        // Get the characters
        c = fgetc(fptr1);
    }
  
    // Print the bytes as string
    printf("%s", str);
  
    // Close the file
    fclose(fptr1);
  
    return 0;
}


Output:



Similar Reads

C Program to Read and Print All Files From a Zip File
To understand how to write a C program for reading and printing zip files, it's important to know what exactly a zip file is. At its core, a zip file contains one or more files compressed using specific compression algorithms.Including the compressed data of the files, the zip file contains meta and header information about all files inside the zip
6 min read
C Program to Read Content of a File
In C, reading the contents of a file involves opening the file, reading its data, and then processing or displaying the data. Example Input: File containing "This is a test file.\nIt has multiple lines." Output: This is a test file.It has multiple lines. Explanation: The program reads and displays the multiline text from the file. In this article,
8 min read
JavaScript Program to read text File
Given a text file, write a JavaScript program to extract the contents of that file. There is a built-in Module or in-built library in NodeJs that handles all the reading operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for reading operations is written. Import fs-module in the program and use functio
2 min read
Slack Bytes in Structures : Explained with Example
Structures: Structures are used to store the data belonging to different data types under the same variable name. An example of a structure is as shown below: struct STUDENT { char[10] name; int id; }; The memory space for the above structure would be allocated as shown below: Here we see that there is no empty spaces in between the members of the
3 min read
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild
2 min read
Read/Write Structure From/to a File in C
For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data. Writing Structure to a File using fwrite We can use fwrite() function to easily write a structure in a
3 min read
cJSON - JSON File Write/Read/Modify in C
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language. JSON in C JSON in C can be handled using
6 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
How to Read a Struct from a Binary File in C?
The structure in C allows the users to create user-defined data types that can be used to group data items of different types into a single unit. We can save this structure in a file using C file handling. In this article, we will learn how we can read a struct from a binary file in C. Read a Struct from a Binary File in CTo read a struct from a bi
2 min read
How to Read From a File 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. In this article, we will explore how to read from a file in C usin
2 min read
How to Read a File Line by Line in C?
In C, reading a file line by line is a process that involves opening the file, reading its contents line by line until the end of the file is reached, processing each line as needed, and then closing the file. In this article, we will learn how to read a file line by line in C. Reading a File Line by Line in CIn C, the fgets() function is a standar
2 min read
How to Hide the Console Window of a C Program?
The task is to hide the console window of a C program. The program for the same is given below. Note: The results of the following program can only be seen when it is executed on a console. C/C++ Code // C program to hide the console window #include <stdio.h> #include <windows.h> int main() { HWND myWindow = GetConsoleWindow(); printf(
2 min read
C Program to Hide a Console Window On Startup
Here in this article, we have created a console application that will write into a file. This console application will work in the background by hiding the console window. To ensure that the program or the console application is still running, we can see the live data appended in the text file created by the program. Console Window The console is l
4 min read
C program to reverse the content of the file and print it
Given a text file in a directory, the task is to print the file content backward i.e., the last line should get printed first, 2nd last line should be printed second, and so on.Examples: Input: file1.txt has: Welcome to GeeksforGeeks Output: GeeksforGeeks to WelcomeGeeksforGeeks Input: file1.txt has: This is line one This is line two This is line t
3 min read
C program to check whether the file is JPEG file or not
Write a C program which inputs a file as a command-line arguments and detects whether the file is JPEG(Joint Photographic Experts Group) or not. Approach: We will give an image as a command line argument while executing the code. Read the first three bytes of the given image(file). After reading the file bytes, compare it with the condition for JPE
2 min read
C program to copy contents of one file to another file
[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) { printf("Cannot open fi
1 min read
Lex Program to print the total characters, white spaces, tabs in the given input file
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The commands for executing the lex program are: lex abc.l (abc is the file name) cc lex.yy.c -lfl ./a.out Let’s see Lex program to print the total charact
1 min read
C program to print odd line contents of a File followed by even line content
Pre-requisite: Basics of File Handling in C Given a text file in a directory, the task is to print all the odd line content of the file first then print all the even line content. Examples: Input: file1.txt: Welcome to GeeksforGeeks Output: Odd line contents: Welcome GeeksforGeeks Even line contents: to Input: file1.txt: 1. This is Line1. 2. This i
2 min read
C Program to print contents of file
In C, reading the contents of a file involves opening the file, reading its data, and then processing or displaying the data. Example Input: File containing “This is a test file.\nIt has multiple lines.” Output: This is a test file.It has multiple lines. Explanation: The program reads and displays the multiline text from the file. In this article,
7 min read
How to clear console in C language?
It is one of the basic need a program may required i.e clear the console during execution time. Need of a clear console screen : A console screen must be cleared once its stated objectives have been completed. A user also needs a clear screen for new data. Like any other language, C offers a variety of ways to clear the console screen. The clear sc
7 min read
How to print range of basic data types without any library function and constant in C?
How to write C code to print range of basic data types like int, char, short int, unsigned int, unsigned char etc? It is assumed that signed numbers are stored in 2's complement form. We strongly recommend to minimize the browser and try this yourself first. Following are the steps to be followed for unsigned data types. 1) Find number of bytes for
4 min read
How to input or read a Character, Word and a Sentence from user in C?
C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. The main features of the C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating system
4 min read
C Program to Print the Program Name and All its Arguments
The command-line argument (CLA) is the parameter provided in the system upon request. Command-line conflict is an important concept in system C. It is widely used when one needs to control your system from the outside. Command-line arguments are transferred to the main () path. Argc calculates the number of arguments in the command line and argv []
2 min read
Print "Hello World" in C/C++ without using any header file
Write a C/C++ program that prints Hello World without including any header file. Conceptually it's seems impractical to write a C/C++ program that print Hello World without using a header file of "stdio.h". Since the declaration of printf() function contains in the "stdio.h" header file. But we can easily achieve this by taking the advantage of C p
2 min read
How to read a PGMB format image in C
PGM or Portable Gray Map file is a grayscale image where each pixel is encoded with 1 or 2 bytes. It contains header information and pixel grayscale values in a matrix form. Approach: The idea is followed to read PGMB format image is as follows: Open a PGMB (binary format PGM image).Extract the pixel information, which can be then used for further
5 min read
Input-output system calls in C | Create, Open, Close, Read, Write
System calls are the calls that a program makes to the system kernel to provide the services to which the program does not have direct access. For example, providing access to input and output devices such as monitors and keyboards. We can use various functions provided in the C Programming language for input/output system calls such as create, ope
10 min read
How to Read Data Using sscanf() in C?
In C, sscanf() function stands for "String Scan Formatted". This function is used for parsing the formatted strings, unlike scanf() that reads from the input stream, the sscanf() function extracts data from a string. In this article, we will learn how to read data using sscanf() function in C. Example: Input: char *str = "Ram Manager 30";Output:Nam
2 min read
How to Read a Paragraph of Text with Spaces in C?
In C, we may need to read the input entered by the user that includes the paragraph of text with spaces. In this article, we will learn how to read a paragraph of text with spaces in C. Reading a Paragraph with Space in CIn C, reading a paragraph of text that includes spaces can be done by using fgets function, This function reads a line from the s
2 min read
How to Read Input Until EOF in C?
In C, reading input until the End of the File (EOF) involves reading input until it reaches the end i.e. end of file. In this article, we will learn various methods through which we can read inputs until EOF in C. Reading Input Until EOF Read Input Until EOF Using getchar()Read Input Until EOF Using fgets()Read Input Until EOF Using scanf()Read Inp
5 min read
C program to print a string without any quote (single or double) in the program
Print a string without using quotes anywhere in the program using C or C++. Note : should not read input from the console. The idea is to use macro processor in C (Refer point 6 of this article). A token passed to macro can be converted to a string literal by using # before it. C/C++ Code // C program to print a string without // quote in the progr
1 min read