I have problem with getNumber function, because my output_file contains zeros. And in my opinion it should not. I want my program to print all numbers and then add them up.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define CHUNK 12
char *getNumber(FILE *infile);
int main(int argc, char *argv[])
{
char *number, *pEnd;
FILE *infile, *outfile;
int newNumber, sum = 0;
if(argc != 3)
{
printf("Missing argument!\n");
exit(1);
}
infile = fopen(argv[1], "r");
if(infile != NULL)
{
outfile = fopen(argv[2], "w");
if(outfile == NULL)
{
printf("Error, cannot open the outfile!\n");
abort();
}
else
{
while(!feof(infile))
{
number = getNumber(infile);
if(number == NULL)
{
free(number);
abort();
}
newNumber = strtol(number, &pEnd, 10);
sum += newNumber;
if(!*pEnd)
printf("Converted successfully!\n");
else printf("Conversion error, non-convertible part: %s", pEnd);
fprintf(outfile, "%d\n", newNumber);
free(number);
}
fprintf(outfile, "\nSum: %d\n", sum);
}
}
else
{
printf("Error, cannot open the infile!\n");
abort();
}
fclose(infile);
fclose(outfile);
return 0;
}
char *getNumber(FILE *infile)
{
char *number, *number2;
int length, cursor = 0, c;dwwd
number = (char*)malloc(sizeof(char)*CHUNK);
if(number == NULL)
{
printf("Error!\n");
return NULL;
}
length = CHUNK;
while(!isspace(c = getc(infile)) && !feof(infile))
{
if(isdigit(c))
{
number[cursor] = c;
cursor++;
if(cursor >= length)
{
length += CHUNK;
number2 = (char*)realloc(number, cursor);
if(number2 == NULL)
{
free(number);
return NULL;
}
else number = number2;
}
}
}
number[cursor] = '\0';
return number;
}
I would be really grateful for any help.
I am also sending two files, input_file and output_file: