#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LINES 10 // Number of lines
#define CHARS 10 // Number of characters at line
char randomChar()
{
#if 0
float f = rand();
f /= RAND_MAX;
return (char) (10 * f + '0');
#else
static char n = 'A';
if (++n > 'Z' && n < 'a')
n = 'a';
if (n > 'z')
n = 'A';
return n;
#endif
}
void getputChar(FILE* infile, FILE* outfile)
{
char ch;
ch = fgetc(infile);
if (ferror(infile))
perror("Error reading file f1.txt");
fputc(ch, outfile);
if (ferror(outfile))
perror("Error writing file f2.txt");
}
int reverseOrder(FILE* infile, int pos, FILE* outfile)
{
int npos = pos;
char ch;
int count;
int n;
while (1) {
ch = fgetc(infile);
if (ferror(infile))
perror("Error reading file f1.txt");
if (ch == '\n') {
count = reverseOrder(infile, npos+1, outfile) + 1;
fseek(infile, pos, SEEK_SET);
if (ferror(infile))
perror("Error seeking file f1.txt");
for (n = 0; n < count; ++n)
getputChar(infile, outfile);
fputc('\n', outfile);
if (ferror(outfile))
perror("Error writing file f2.txt");
return count;
}
else if (ch == EOF) {
if (npos - pos == 0)
return 0;
else {
fseek(infile, pos, SEEK_SET);
if (ferror(infile))
perror("Error seeking file f1.txt");
getputChar(infile, outfile);
fputc('\n', outfile);
if (ferror(outfile))
perror("Error writing file f2.txt");
return 1;
}
}
else {
npos++;
}
}
}
int main()
{
FILE* file_ptr;
FILE* file_ptr1;
int n, nn;
// Creating file f1.txt
file_ptr = fopen("f1.txt", "w");
if (file_ptr == NULL) {
perror("Error creating file f1.txt");
}
srand(time(0));
for (n = 0; n < LINES; ++n) {
for(nn = 0; nn < CHARS; ++nn) {
fputc(randomChar(), file_ptr);
if (ferror(file_ptr)) {
perror("Error writing file f1.txt");
}
}
fputc('\n', file_ptr);
}
fclose(file_ptr);
// Reverse order of lines
file_ptr = fopen("f1.txt", "r");
if (file_ptr == NULL) {
perror("Error opening file f1.txt");
}
file_ptr1 = fopen("f2.txt", "w");
if (file_ptr1 == NULL) {
perror("Error creating file f2.txt");
}
reverseOrder(file_ptr, 0, file_ptr1);
fclose(file_ptr1);
fclose(file_ptr);
printf("OK\n");
return EXIT_SUCCESS;
}