Did you not learn something from the last time we went through this issue?
Remember, (virtually) all complex problems can be broken down into a series of smaller, simpler ones.
Often the important step is to identify where/how the original problem can be broken down into smaller tasks. This skill improves with experience, though it is also a necessary way to look at the problem in order to minimize the time taken to solve it and debug it.
Applying this technique to your current question may be a worth exercise.
Summary of requirements/observations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. We need to extract the values from each line of a text file
2. These values may be duplicated - we only want to store a single instance of each value.
3. Since values may be duplicated, we have no direct way of determining the number of unique values, HOWEVER - we do know that it must be less than (or equal to) the number of lines in the input file.
Choices:
1. Management of duplicate values
---------------------------------
A. only maintain a list of distinct values. This will require examining as-many-as all previous values for each line of the input file that we process. Line 1 will need to be compared against 0 previous values. Line 1000 will need to be compared to up to 999 lines - less if the PID is found early, 999 compares if it isn't found.
B. retain all values, sort, copy 1 instance of each distinct value found to a new list.
C. Use a stl datastructure that will take care of duplicates for you (std::map comes to mind, though I've never used it)
2. Extraction of data items
---------------------------
A. tokenize the line, extract and use the tokens that you need - more complex & robust
B. extract the required elements directly - simpler and more error-prone.
Here's some code I smashed together while the kettle was boiling.
It will
(a) count the number of lines in the file
(b) display the COMMAND and PID columns of each line
You'll have to work out your preferred method for each of the 2 choices I've outlined above.
Good luck!
#include <cstdio>
int countTextFileLines(char *filename)
{
int i=0;
char lineBuffer[1024];
FILE *fp = fopen(filename, "rt");
while (fgets(lineBuffer, 1024, fp))
i++;
fclose(fp);
return i;
}
void displayPIDcolumn(char *filename)
{
int pID;
char lineBuffer[1024], cmdBuffer[20];
FILE *fp = fopen(filename, "rt");
while (fgets(lineBuffer, 1024, fp))
{
sscanf(lineBuffer, "%9s %5d", &cmdBuffer, &pID);
printf("CMD: %s PID: %d\n", cmdBuffer, pID);
}
}
int main()
{
char *filename = "topListing.txt";
printf("%s has %d lines.\n", filename, countTextFileLines(filename));
displayPIDcolumn(filename);
return 0;
}