Basically I am asked to reinvent the wheel a.k.a. the uniq commmand. I have to write a code that returns the number of occurence of each line in a file. I've done it a lot of times in Python and Java with a simple

for line in file
    if given_line == line;
    count += 1

but I am starting to think that there is no magic thing as

for...in...

in C. I know how to get the total number of lines with

while (!feof(f)){
    fgets(line, sizeof(line), f);
    count += 1;
    {

So I am very much confused. I simply want to figure it out now so I will not be stuck on such a newbie problem in the future. Thanks to everybody in advance.

Recommended Answers

All 3 Replies

So I am very much confused. I simply want to figure it out now so I will not be stuck on such a newbie problem in the future.

What exactly is the confusion? If you are able to extract lines, use strcmp() to compare strings. Is this what you wanted? Maybe i didn't completely understand your question.

strcmp will not do good, u have to use strstr() function with loop and if condition which say "strstr(s1,s2)==null" to count the given string line in the file,strstr is available in string.h

strcmp will not do good, u have to use strstr()

If you want to count exact full lines then strcmp() is better. If you want to count lines containing a substring then strstr() is better. The two accomplish different goals.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.