Skip to content
Related Articles

Related Articles

Sorting strings from the text file

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 24 Nov, 2020
Improve Article
Save Article

Given a text file “file.txt” that consists of strings, the task is to sort all the strings in alphabetical order in that text file.

Approach: The idea is to use the concept of File Handling and a text file(say file.txt) that contains all the strings. Below are the steps:

Below is the implementation of the above approach:


// C++ program to sort given array
// of string stored in a file
#include <bits/stdc++.h>
#include <cstdlib>
#include <cstring>
#include <fstream>
using namespace std;
// Driver Code
int main()
    int N, i, j;
    // File pointer to open file
    FILE* f;
    // fopen() for creating of a file
    f = fopen("file.txt", "w");
    // Input number of strings
    // to be inserted in file
    cin >> n;
    vector<int> name(N);
    // Insert the strings into file
    for (i = 0; i < n; i++) {
        // Insert names in file
        cin >> name[i];
        // Writing into the file
        fprintf(f, "%s", name[i]);
    // Close the file
    // Reopening in read mode
    f = fopen("file.txt", "r");
    // Check does file exist or not
    if (f == NULL) {
        cout << "File doesn't exist!";
        return 0;
    // Read the file until it
    // encounters end of line
    while (!feof(f)) {
        fscanf(f, "%s", name[i]);
    n = i - 1;
    // Sort the strings
    sort(name.begin(), name.end());
    // Insert the strings into file
    // after sorting
    for (i = 0; i < n; i++) {
        // Write into the file
        fprintf(f, "%s", name[i]);
    // Print the sorted names
    for (i = 0; i < n; i++) {
        cout << name[i] << '\n';
    return 0;

Input File:

Output File:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!