I am currently trying to work on a program that will read in a file line by line and place the content in an array. Then trying to reverse the original array into a second array so I can later compare the two arrays. My current code is
#include <stdio.h>
#include <string.h>
void reversing(char buffer[], char reverse[], int stringLength);
int main(int argc, char const *argv[])
{
int stringLength = 0;
FILE *fp; //Declaring a FILE type pointer calling it fp
char buffer[64]; //Declaring a char array the size of 64 named buffer
fp = fopen("./test.txt", "r");
if(fp == NULL)
{
printf("File did not open!\n");
}
else
{
while(fgets(buffer, 64, (FILE*)fp) != NULL)
{
printf("\nNormal String: %s", buffer); //Print content in buffer(original array)
stringLength = strlen(buffer); //Storing the length of the readed input
char reverse[stringLength]; //Creating array for reversed comparision(comparision not implemented yet)
printf("String length: %d\n", stringLength); //Print string length(for debugging)
reversing(buffer, reverse, stringLength);
printf("Reversed String: %s\n", reverse);//Print content in reverse(Reverse array)
}
printf("\n\nEND OF FILE Reached!\n");
fclose(fp);
}
return 0;
}
void reversing(char buffer[], char reverse[], int stringLength)
{
int i = 0;
int j = stringLength - 1;
while(i < j)
{
reverse[j] = buffer[i];
i++;
j--;
}
}
My test file is simply
A
AB
ABC
ABCD
ABCDE
It should print to the screen
Normal String: A
Reversed String: A
Normal String: AB
Reversed String: BA
Normal String: ABC
Reversed String: CBA
Normal String: ABCD
Reversed String: DCBA
Normal String: ABCDE
Reversed String: EDCBA
When I run the program through a debugger it shows that once inside the reversing function the letters are being swap correctly; however, once it exits the function and the call to print the reversed array is made it is printing garbage, but inside the garbage are the first two elements swap correctly. Any help of suggestion would be greatly appreciated.
As a side note
I am trying to make this as simple as possible since the true objective or this program is to take it and implement it in assembly on a ci20 machine.