3

When trying to read a plain text file with fgets in C, i get some strange looking output on the first line. So if the first line is meant to be "hello" it comes out as something like "ELFh` �� 20120918 (prerelease)@xxhello". Here is the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fr;
    int i;
    extern int uniq(char *previous_word, char *current_word);
    char *line1 = malloc(500);
    char *line2 = malloc(500);
    char *temp;
    for(i = 0; i<argc; i++)
    {

        fr = fopen (argv[i], "r");
        while(fgets(line2, 499, fr) != NULL)
        {
            uniq(line1, line2);
            temp = line1;
            line1 = line2;
            line2 = temp;
        }
        fclose(fr);
    }
    return 0;
}
int uniq(char *previous_word, char *current_word) {
    if(!(current_word))
        return 1;
    if(strcmp(previous_word, current_word))
        printf("%s", current_word);
    return 0;
}

I've searched every description i can give of this problem on google and stack overflow and i can find nothing at all that fixes it.

Khodeir
  • 465
  • 4
  • 15
  • 3
    That ELF looks like you are reading a Linux executable. – rekire Oct 31 '12 at 06:14
  • 1
    Note that `argv[0]` is your application name executable and not the first argument passed to your application, as you are assuming. Check out this thread: http://stackoverflow.com/questions/2020945/argc-and-argv-in-main – Jack Oct 31 '12 at 06:23

1 Answers1

4

Your loop must begin at index 1. argv[0] is your executable.

To check argv[0] is helpful if you have a so called multi binary executable. There you can handle different commands with just one binary. This is very helpful on embedded systems where you need to save memory.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
rekire
  • 47,260
  • 30
  • 167
  • 264