Skip to content

Instantly share code, notes, and snippets.

@tomleo
Created December 31, 2012 16:01
Show Gist options
  • Save tomleo/4420889 to your computer and use it in GitHub Desktop.
Save tomleo/4420889 to your computer and use it in GitHub Desktop.
Add a file of numbers togeather
int getTotal(char *nameOfFile)
{
FILE * fin = fopen(nameOfFile, "r"); //this can be done in one line
int total=0;
int c;
if(fin == NULL)
perror("Error opeining file");
while((c = fgetc(fin)) != EOF)
{
//fgetc will read newlines which are at the end of every line
//the while loop does not exit before the \n is read
if(c == '\n')
break;
total += (int)(c - '0');
//the - '0' or 48 is what changes an ascii value to integer val
/*The reason atoi doesn't work in this case is because
atoi takes a NULL-terminated character pointer.
In this case you are only reading a single char at a time
so atoi gives you a segmentation fault*/
}
return total;
}
int main(int argc, char *argv[])
{
int total;
total = getTotal(argv[1]);
printf("The Total is: %d\n", total);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment