I'm trying to use the data from a .txt file to get the sum of all the values. I used the function fgets to get all the values. How can I sum all the values?? I tried to make an array for every line in order to sum but I couldnt get it. Hier is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 256
// La máxima cantidad de líneas que puede tener
#define TOTAL_LINES 52
#define FILE_NAME "test.txt"
int main()
{
char all_lines[TOTAL_LINES][MAX_STRING_LENGTH];
char buferFile[MAX_STRING_LENGTH];
FILE *document = fopen(FILE_NAME, "r");
if (document == NULL)
{
printf("File cannot be open");
return 0;
}
int index = 0;
while (fgets(buferFile, MAX_STRING_LENGTH, document))
{
strtok(buferFile, "\n");
memcpy(all_lines[index], buferFile, MAX_STRING_LENGTH);
index ;
}
fclose(document);
char line1[MAX_STRING_LENGTH];
strcpy(line1,all_lines[1]);
char *token;
int j = 0;
token = strtok(line1, " ");
char *array[256];
while( token != NULL ) {
array[j ] = token;
token = strtok(NULL, " ");
}
for (j = 0; j < 256; j )
printf("\n%s", array[j]);
return 0;
}
Hope you can help me.
CodePudding user response:
You're loading strings into a 2D array, then storing pointers (array[]
) to a copy of only the 2nd line you've loaded (all_lines[1]
). It's not easy to see what your objective is, but I offer this for educational purposes...
void main( void ) {
char buf[ 256 ];
char *fName = "test.txt";
FILE *fp = fopen( fName, "r" );
if( fp == NULL ) {
printf( "Cannot open '%s'\n", fName );
return;
}
int accum = 0;
while( fgets( buf, sizeof(buf), fp ) ) {
for( char *tok = buf; ( tok = strtok( tok, " ") ) != NULL; tok = NULL )
accum = atoi( tok );
}
fclose( fp );
}
Update:
In response to a question from the OP, here's an alternative, expanded version of that one line for()
loop tokenising each row read-in:
char *tok = buf;
while( ( tok = strtok( tok, " ") ) != NULL ) {
accum = atoi( tok );
tok = NULL;
}
The 1st time strtok()
is called, 'tok' is pointing at 'buf'. For each subsequent call, the value of 'tok' is NULL...