Commit ff430f14 by jobrod

Add new file

parents
Showing with 136 additions and 0 deletions
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RECORDS 50
#define MAX_LINE_LENGTH 20
typedef struct
{
char jr[4];
int number;
char hex[10];
} Record;
int read_file(const char *filename, Record records[], int *length);
void write_file(const char *filename, Record records[], int length);
void convert_to_hex(int number, char *hex);
int is_faulty_record(const char *line);
int get_file_length(const char *filename);
int main()
{
Record records[MAX_RECORDS];
int length = 0;
int file_length = get_file_length("AN.txt");
printf("Length of the file: %d lines\n", file_length);
if (read_file("AN.txt", records, &length) != 0)
{
printf("Error reading input file.\n");
return 1;
}
for (int i = 0; i < length; i++)
{
convert_to_hex(records[i].number, records[i].hex);
}
write_file("TUL.txt", records, length);
printf("Processed Records:\n");
printf("Jnr. I Number I Hex\n");
for (int i = 0; i < length; i++)
{
printf("%-4d I %-6d I %-4s\n", i + 1, records[i].number, records[i].hex);
}
return 0;
}
int read_file(const char *filename, Record records[], int *length)
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
return 1;
}
char line[MAX_LINE_LENGTH];
int index = 0;
while (fgets(line, sizeof(line), file) != NULL)
{
if (is_faulty_record(line))
{
printf("Faulty record detected: %s", line);
continue;
}
sscanf(line, "%3s %d", records[index].jr, &records[index].number);
records[index].jr[3] = '\0'; // Ensure null termination
index++;
if (index >= MAX_RECORDS)
{
break;
}
}
*length = index;
fclose(file);
return 0;
}
void write_file(const char *filename, Record records[], int length)
{
FILE *file = fopen(filename, "w");
if (file == NULL)
{
printf("Error opening output file.\n");
return;
}
fprintf(file, "Jnr. I Number I Hex\n");
for (int i = 0; i < length; i++)
{
fprintf(file, "%-4d I %-6d I %-4s\n", i + 1, records[i].number, records[i].hex);
}
fclose(file);
}
void convert_to_hex(int number, char *hex)
{
sprintf(hex, "%X", number);
}
int is_faulty_record(const char *line)
{
char jr[4];
int number;
if (sscanf(line, "%3s %d", jr, &number) != 2 || number >= 4444)
{
return 1;
}
return 0;
}
int get_file_length(const char *filename)
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
return -1;
}
int count = 0;
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), file) != NULL)
{
count++;
}
fclose(file);
return count;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment