0

I have some code here:

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

    int main (int argc, char *argv[])
    {
        char c;

        FILE *fp;

        fp = fopen(argv[1], "r");

        if (fp == NULL)
        {
            printf ("Errore nell'apertura del file %s\n\n", argv[1]);
            exit(EXIT_FAILURE);
        }

        while ( (c = getc(fp)) != EOF)
        {
            if (strcmp(c,argv[2]) == 0)
            {
                c = argv[3];
            }

            putchar(c);
        }

        return 0;
    }

First question: i have to replace some characters in argv[2] on my file (argv[1]) with some other characters on argv[3]... i know that c = argv[3] is a BIG wrong horror thing but... how can i replace my "c" with the character i wrote in argv[3]??

EX: out.exe file.txt a b
    ------  -------- - -
    program file     1 2
    name    name     letters

Second question: if in argv[2] i have 2 char, the first is the character to replace and the second is the one with which i have to replace, how can i write it??

EX: out.exe file.txt ab
    ------  -------- --
    program file     1/2
    name    name     letters (both on argv[2])
Lc0rE
  • 2,236
  • 8
  • 26
  • 34
  • 1
    As an aside: for `while ( (c = getc(fp)) != EOF)` you should make `c` an `int`, not a `char`. With `char`, the loop could stop early if `char` is signed, and won't stop at all if `char` is unsigned. – Daniel Fischer Jun 21 '12 at 20:14
  • you should check that `argc == 4` – jfs Jun 21 '12 at 20:17

1 Answers1

3

argv is an array of pointers to char. argv[n] returns a pointer to char, not a char. If you want to get the first char that the pointer argv[n] points to then dereference it:

char c = *(argv[n]) // or argv[n][0]

I believe that should answer your second question as well.

Ed S.
  • 122,712
  • 22
  • 185
  • 265