please help me with the flowchart of this question ,Write a program, called sort
ID: 3670033 • Letter: P
Question
please help me with the flowchart of this question ,Write a program, called sort_file, which takes a text file as input and produces an output file which has all the original lines in alphabetical order. The program should do the following: Prompt the user for the names of the input and output files. You can prepare an input file with appropriate unsorted data. A simple file with one word per line will suffice. Declare and define three functions to perform the following tasks: Read the data from the input file into an array. Sort the array using the bubble sort algorithm. Write the sorted data array to the output file
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Read the data from the input file into an array. Sort the array using the bubble sort algorithm. Write the sorted data array to the output file
void get_input(char filename[],char content[][100], int* n)
{
FILE * fp;
int read;
char* line = NULL;
size_t len = 0;
fp = fopen(filename, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1)
{
if(line[read-1]==' ')
line[read-1] = '';
strcpy(content[*n],line);
*n = *n+1;
}
fclose(fp);
if (line)
free(line);
}
void sort(char content[][100],int n)
{
int i;
int j;
for(i=n-1;i>=0;i--)
{
for(j=0;j<i;j++)
{
if(strcmp(content[j],content[j+1])>0)
{
char temp[100];
strcpy(temp, content[j]);
strcpy(content[j],content[j+1]);
strcpy(content[j+1],temp);
}
}
}
}
void print_output(char filename[], char content[][100], int n)
{
FILE * fp;
fp = fopen(filename, "w");
int i=0;
while(i!=n-1)
{
fputs(content[i],fp);
fputs(" ",fp);
i++;
}
fputs(content[i],fp);
fclose(fp);
}
int main()
{
char content[100][100];
int n=0;
char file_input[100],file_output[100];
printf("Enter name of input file:: ");
scanf("%s",file_input);
get_input(file_input,content,&n);
sort(content,n);
printf("Enter name of output file:: ");
scanf("%s",file_output);
print_output(file_output,content,n);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.