In the text file numbers.txt there is a series of integers separated by commas. Assume that the file is formatted correctly (no letters, spaces, etc., no commas after the last number). However, there is one small problem: these numbers can be significantly larger than the largest value that can be represented by the int type, and even long long can also be negative.
It is necessary to create a program that reads numbers from a file, finds the largest number in the file, and prints it on the screen. It is forbidden to use any arrays or strings in the program.
The program works but for positive inputs, but for negative i don't get any output.
It is necessary to create a program that reads numbers from a file, finds the largest number in the file, and prints it on the screen. It is forbidden to use any arrays or strings in the program.
The program works but for positive inputs, but for negative i don't get any output.
C:
#include <stdio.h>
int main() {
// Open the file "brojevi.txt" for reading
FILE *input = fopen("brojevi.txt", "r");
if (!input) {
// Print an error message if the file cannot be opened
printf("Error!\n");
return 1;
}
char current, previous, temp;
int counter = 0;
long position = ftell(input), maxPosition = ftell(input);
int maxCounter = 0;
int i;
char tempChar = ' ';
char sign = '+';
// Read characters from the file until the end
do {
current = fgetc(input);
sign = (current == '-') ? '-' : sign;
position = (tempChar == ',') ? ftell(input) - 1 : position;
if (current == ',' || current == EOF) {
// Check for the end of a sequence and update maximum if needed
if (sign == '+' && counter > maxCounter) {
maxCounter = counter;
maxPosition = position;
} else if (sign == '-') {
if (maxCounter == 0 || (counter < maxCounter && maxCounter != 0)) {
maxCounter = counter;
maxPosition = position - 1;
}
} else if (counter == maxCounter) {
for (i = 0; i < maxCounter; i++) {
fseek(input, position + i, SEEK_SET);
previous = fgetc(input);
fseek(input, maxPosition + i, SEEK_SET);
temp = fgetc(input);
if ((sign == '+' && previous > temp) || (sign == '-' && previous < temp)) {
maxPosition = position;
break;
}
}
}
counter = -1;
sign = '+';
}
tempChar = current;
counter++;
} while (current != EOF);
// Set the file position to the beginning of the identified sequence
fseek(input, maxPosition, SEEK_SET);
// Print the identified sequence
do {
current = fgetc(input);
if (current != ',' && current != EOF)
printf("%c", current);
} while (current != ',' && !feof(input));
// Close the file
fclose(input);
return 0;
}