Write to files in C

-1

Hey guys. I need to do a job in C that I have to create files with numeric sequences and create another file with the intersection of these numbers and such ... But I can not write these (int) in the file, type, it has to be 10 values , but at the time of execution I end up coming with much more values than expected.

    printf("Entre com os valores do arquivo: \n");
    for(cont=1; cont <= *argv[3]; cont++) {
        scanf("%c", &ch);
        fputc(ch, f1);
    }

* argv [3] is the size that user entered for the amount of values.

    
asked by anonymous 14.01.2018 / 22:04

1 answer

0

The problem is how you are using the argv parameter on your for :

for(cont=1; cont <= *argv[3]; cont++) {
-----------------------^ aqui

argv is actually an array of strings that is usually declared as:

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

Soon *argv[3] will actually give the first caratere of the third parameter that will be converted to integer based on its ASCII value. So if you call the program with:

programa.exe param1 param2 20

The 20 will stay in arg[3] as an array of characters, and argv[3][0] or *argv[3] will give '2' , which converted to integer will give 50 .

If you want to use the third parameter for integer you can do the conversion using atoi :

for(cont=1; cont <= atoi(argv[3]); cont++) {

In addition, reading with %c will not read the Enter pressed, which will be for the next reading, resulting in fewer readings than desired. A simple solution is to start reading with a space before %c :

scanf(" %c", &ch);

Documentation for the atoi function

    
15.01.2018 / 01:45