-3

This is the part of the code I need help with -

include <stdlib.h>
include <time.h>
include <stdio.h>
include "aes.h"

void encrypt(const char *fileIn, const char *fileOut,
const unsigned char *key);

void decrypt(const char *fileIn, const char *fileOut,
const unsigned char *key); 

int main()
{
const unsigned char key[] = "my key";
srand(time(NULL));

aes_init();
encrypt( "main.c", "main.c.encrypted", key);
decrypt("main.c.encrypted", "main.c.decrypted", key); 
return 0;
}

Right now, what I do is, every time before running the program is... I go to the code and change the name of the file like..

encrypt("main.c", "main.c.encrypted", key);
decrypt("main.c.encrypted", "main.c.decrypted", key);

or

encrypt("trial.doc", "trial.doc.encrypted", key);
decrypt("trial.doc.encrypted", "trial.doc.decrypted", key);

However, I would like for the user to be able to enter these file names when the program is run.

HOW CAN I DO THAT?

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Anki Ju
  • 1
  • 4

2 Answers2

1

For passing arguments to the program,

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

is the main prototype you want to use, and then you can get at the argument count and arguments themselves.

For example, the following C program prints out all its arguments, including the one representing the executable:

#include <stdio.h>
int main (int argc, char *argv[]) {
    for (int i = 0; i < argc; i++)
        printf ("argv[%d] = '%s'\n", i, argv[i]);
    return 0;
}

If you run it with:

./myprog three point one four one five nine

you'll see the output:

argv[0] = './myprog'
argv[1] = 'three'
argv[2] = 'point'
argv[3] = 'one'
argv[4] = 'four'
argv[5] = 'one'
argv[6] = 'five'
argv[7] = 'nine'

The other alternative is to enter them from within the program and, for that, you can use a safe input function such as the one shown here.

A safe input function will generally use fgets() to ensure there's no chance of buffer overflow. The function linked to above has all sorts of other handy features like end-of-file detection, handling of lines that are too long (detecting and correcting) and prompting.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

How about using scanf(), so the user can run the program and enter desired file names?

printf("Please enter file name to encrypt: ");
char name[80];
scanf("%s", name);

then you can copy the string and concat with ".encrypted" or ".decrypted" string like described here: C String Concatenation

Community
  • 1
  • 1
Virus_7
  • 580
  • 4
  • 8
  • 1
    You have to be careful with scanf() to input strings: you should use fgets() instead, as it allows you to specify the size of the string. fgets(buffer, 80, stdin) is probably a better solution. – Teo Zec May 21 '14 at 05:55