Reputation: 85
I have this function that saves in an integer variable all the numbers from a text file. But I want to make a change so that I can save just the second number in each line into a vector and then print the whole vector. Here is an example of the file.txt
:
123 19
321 18
432 9
876 16
875 17
And here is the code that must be changed:
void LerVetor(int *V, int *N)
{
FILE *fp;
int marks;
fp = fopen("dados3.txt", "r");
if (fp == NULL)
printf("Falha ao abrir ficheiro\n");
rewind(fp);
do
{
fscanf(fp, "%d", &marks);
printf("%d\n", marks);
} while (!feof(fp));
fclose(fp);
}
The output is the same as the file.txt
because the code just prints the content of the file.
Resume: Save just the second numbers of each line, ex: 19
, 18
, 9
..., in a vector and then print the vector.
Upvotes: 1
Views: 373
Reputation: 23802
One way you can do it is to pass a pointer to the vector (array of ints) where you need to store the values as a parameter of the function.
To dispose the first value in every line you can use a discard specifier %*d
:
#include <stdio.h>
void LerVetor(int* vector)
{
FILE *fp;
if (!(fp = fopen("dados3.txt", "r"))){
perror("Falha ao abrir ficheiro"); //print eventual open file error
return;
}
// keep reading lines discarding first value with %*d avoiding container overflow
for(int i = 0; fscanf(fp, "%*d %d", &vector[i]) == 1 && i < 100; i++)
printf("%d\n", vector[i]); //printing vector values
fclose(fp);
}
int main(void)
{
int vector[100];
LerVetor(vector);
return 0;
}
Upvotes: 1
Reputation: 16540
the following proposed code:
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
void LerVetor( void )
{
FILE *fp = fopen("dados3.txt", "r");
if( !fp )
{
perror("fopen to read: dados3.txt failed");
exit( EXIT_FAILURE );
}
int marks;
int dummy;
while( fscanf(fp, "%d %d", &dummy, &marks) == 2 )
{
printf("%d\n", marks);
}
fclose(fp);
}
Upvotes: 2