Skip to content
Related Articles

Related Articles

Sorting strings from the text file
  • Last Updated : 24 Nov, 2020

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++



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
    fclose(f);
  
    // 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]);
        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;
}

chevron_right


Input File:

Output File:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :