I am currently learning C programming (my experience is in Python, Java and Swift). I am trying to count how many numbers are on the first line of a text file.
The text file looks a bit like this:
-54 37 64 82 -98
...
I have tried various different ideas that I have had. The first was to check each character in turn for the EOL, and if it wasn't to add 1 to the total. I quickly realised this only works for single digit numbers, and not general integers.
I then tried to use fscanf
to find the last number on the line, and then rewind and use fscanf to count each number until that last number was found again:
int temp;
FILE *fd = fopen("test.txt", "r");
fscanf(fd, "%d\n", &temp);
printf("Last Number on Line is: %d\n", temp);
However before I could even write the next logic to count the numbers I realised that this printed Last Number on Line is: -54
which was not the expected output from the above file example.
At this point I am rather stuck. Searching online mainly returns results on how to count how many lines are in a file due to the similarity of the question.
Any help would be much appreciated!
CodePudding user response:
You can use the function fgets
to read a line from the file. Then you can use the function sscanf
to count the number of numbers in the line.
For example let's assume that you already read a line from the file and store it in the array with name s
char s[] = "1 12 123 1234 12345\n";
Now in a loop you can count the number of numbers for example the following way
size_t count = 0;
int pos;
for (const char *p = s; sscanf( p, "%*d%n", &pos ) != EOF; p = pos)
{
count;
}
printf( "count = %zu\n", count );
The output of this code snippet will be
count = 5
If you do not know the maximum size of a record in the file you can dynamically reallocate a character array until fgets
will read the new line character '\n'
and then apply the approach with sscanf
.
CodePudding user response:
In the end I have used the suggestion here and come up with the following solution:
char buffer;
int temp = 0;
int row_count = 0;
while((buffer = getc(fd)) != '\n') {
if (temp == 0 && (isdigit(buffer))) {
col_count = 1;
temp = 1;
} else if (temp == 1 && buffer == ' ') {
temp = 0;
}
}
This is working fine for me in the context I am using it within, thanks for the help