Hello everyone,
I have a little problem with this program.
The purpose of the program is to read 2 lines from a file.
The first line consist a name and the second line a number.
For example
Sergio
12345
Then to the second line of the file is added a new value which comes from addition of a new number and the number from the second line of file.
And this program should be able to use numbers that are max. 300 characters long.
Now when I run this program "normally" the result is rubbish.
But when I run this with debugging line by line the add function it works sometimes just fine. And I also noticed that my CPU processor is under heavy "stress" when i debug the code.
Anyone have an idea what is the reason that this doesnt work?
Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 300
void reverse( char * );
void add( char *, char *, char * );
void reset( char *, int );
void empty( char *, int );
int main () {
FILE * pFile;
long lSize;
char * buffer;
pFile = fopen ( "file.txt" , "r+" );
if (pFile==NULL) {fputs ("File error",stderr);system
("pause"); exit (1);}
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
buffer = (char*) malloc (sizeof(char)*lSize);
fread (buffer,1,lSize,pFile);
rewind(pFile);
fflush(pFile);
char * line1;
char * line2;
line1 = strtok(buffer,"\n");
line2 = strtok(NULL,"\n");
printf("\n%s", line1);
printf("\n%s", line2);
char number[MAX];
char result[MAX+1];
reset(number, MAX);
empty(result, MAX+1);
printf("\nGive another number: ");
fgets(number,MAX,stdin);
if(number[strlen(number)-1] == '\n')
number[strlen(number)-1] = '\0';
else
while(getc(stdin) != '\n');
add(line2,number,result);
printf("\n\n%s",result);
fprintf(pFile, "%s\n", line1);
fprintf(pFile, "%s\n", result);
fclose (pFile);
free (buffer);
fclose(pFile);
system("pause");
return 0;
}
void reverse( char * numb ){
int lSize = strlen(numb);
char * copy = (char *)malloc(( lSize + 1) * sizeof(char));
int i;
for(i=0; i < lSize; i++){
copy[i] = numb[lSize-1 -i];
}
copy[i] = '\n';
for(i=0; i < lSize; i++)
numb[i] = copy[i];
free(copy );
}
void add( char * num1, char * num2, char * num3 ){
int i, j;
int result = 0;
int memoryNum = 0;
int h1, h2;
int lSize = 0;
reverse(num1);
reverse(num2);
if( strlen(num1) >= strlen(num2))
lSize = strlen(num1);
else
lSize = strlen(num2);
for(i=0, j=0; i < lSize; i++,j++){
result = 0;
h1= (int)(num1[i] - '0');
if( h1 < 0){
h1 = 0;
}
h2 = (int)(num2[j] - '0');
if( h2 < 0 ){
h2 = 0;
}
result = h1 + h2 + memoryNum;
memoryNum = 0;
if( result > 9 ){
memoryNum = result / 10;
result = result % 10;
}
num3[i] = (char)(result + '0');
}// for loop
if( memoryNum > 0)
num3[i] = (char)(memoryNum + '0');
reverse(num1);
reverse(num2);
reverse(num3);
}
void reset( char * number, int lSize ){
int i;
for(i=0; i < lSize; i++){
number[i] = '0';
}
}
void empty( char * number, int lSize){
int i;
for(i=0; i < lSize; i++)
number[i] = '\0';
}