← Back to list

Easy way to read input in c and c++ — part 5

Welcome back dear readers. I like to keep writing how easy is to read input in c and c++, working on Linux too. Coding is fun and…

Doritasci · 2025-07-26 16:17 · 0 claps · 4.8 min read
#fopen #fputs #fclose #argv #scanf
Open on Medium ↗
Wiki topics: 💻 · Programming 🔓 · Open Source

Easy way to read input in c and c++ — part 5

Welcome back dear readers. I like to keep writing how easy is to read input in c and c++, working on Linux too. Coding is fun and stressful in equal measure. Anyway it would be best if it were fun and easy. Let me recap some things about the capacity to read inputs from command line:

//--
//C++:
//test1++.cpp
#include <iostream>

int main(int argc, char *argv[]) {    
    std::cout << "argv: " << argv[1] << "\n";
    int number;
    std::cout << "Enter an integer: ";
    std::cin >> number;
    std::cout << "You entered " << number << std::endl;    
    return 0;
}
//--

Output:

$ g++ test1++.cpp -o test1++
$ ./test1++ a
argv: a
Enter an integer: 2
You entered 2
$

Done this, let’s move on to something elaborated:

//--
// C
// test1.c
#include <stdio.h>

void repeat (char c , int count )
{
     for (int i = 0; i<count;i++){
        printf("%c", c);
    }
}

int main(int argc, char *argv[]){
    printf("argv: %s\n", argv[1]);
    //------
    repeat('-' , 40 );
    printf("\n");
    printf("scanf char: ");
    char a[10];  //if you don't declare size, you get an error
    scanf("%s", a);
    printf("you have typed: %s\n", a);
    //------
    repeat('-' , 40 );
    printf("\n");
    printf("scanf int: ");
    int zum;
    int num = scanf("%d", &zum);
    if(num!=1)
        printf("num: %d - you have typed something different than int: %d\n", num, zum);
    else
        printf("num: %d - you have typed int: %d\n", num, zum);
    //------
    repeat('-' , 40 );
    printf("\n");
    char input[] = "Jack Lantern 8.654 1234 abcehnks";
    int i;
    float x;
    char str1[12], str2[8];  
    int output = sscanf(input, "%9s%*s %f %d %9s", str1, &x, &i, str2); 
    printf("---> %s\n", input);    
    printf("Items elaborated = %d \n"  
            "name = %s\n"
            "pin = %d\n"
            "amount = %.2f\n"
            "bank = %c%c%c%c%c\n",
            output, str1, i, x, str2[2], str2[4], str2[0], str2[7], str2[3]);
    printf("\n%0*d\n\n", 40, 0);
    return 0;
}
//--

Terminal:

$ gcc test1.c -o test1
$ ./test1 a
argv: a
----------------------------------------
scanf char: a
you have typed: a
----------------------------------------
scanf int: b
num: 0 - you have typed something different than int: 0
----------------------------------------
---> Jack Lantern 8.654 1234 abcehnks
Items elaborated = 4 
name = Jack
pin = 1234
amount = 8.65
bank = chase

0000000000000000000000000000000000000000

$

The example above is to show the differents form to send data to program. Function scanf() read data from stdin (standard input stream) and stores it into the given arguments. It is defined in the <stdio.h> header file. Do you want have fun with scanf()? Read **this, [this](https://en.cppreference.com/w/c/io/fscanf) and [this](https://c-faq.com/stdio/scanfprobs.html) to learn more about whitespace problem. Because a real programmer open a new tab, always. Function sscanf() **reads formatted input from a string, stores the result in the provided variables and returns the number of input items successfully matched and assigned.

What if I try to do this:

$ ./test1 a >> output.txt

It happens that nothings appears on display except for the blinking cursor waiting for data to be sent:

$ ./test1 a >> output.txt
v
2

The file output.txt will be:

argv: a
----------------------------------------
scanf char: you have typed: v
----------------------------------------
scanf int: num: 1 - you have typed int: 2
----------------------------------------
---> Jack Lantern 8.654 1234 abcehnks
Items elaborated = 4 
name = Jack
pin = 1234
amount = 8.65
bank = chase

0000000000000000000000000000000000000000

Test it again:

$ ./test1 a >> output.txt
r
6

The new content of output.txt will be:

argv: a
----------------------------------------
scanf char: you have typed: v
----------------------------------------
scanf int: num: 1 - you have typed int: 2
----------------------------------------
---> Jack Lantern 8.654 1234 abcehnks
Items elaborated = 4 
name = Jack
pin = 1234
amount = 8.65
bank = chase

0000000000000000000000000000000000000000

argv: a
----------------------------------------
scanf char: you have typed: r
----------------------------------------
scanf int: num: 1 - you have typed int: 6
----------------------------------------
---> Jack Lantern 8.654 1234 abcehnks
Items elaborated = 4 
name = Jack
pin = 1234
amount = 8.65
bank = chase

0000000000000000000000000000000000000000

Is it satisfactory, isn’t it?

Well! Now let us do it with our program, or rather, we write code to send our file output to an external file. Which type of external file? Let’s keep this simple, we will use a file that contains data in the form of ASCII characters, a file with .txt extension, a text file. The simplest form of code is this:

//---
//C
//test2w.c

#include <stdio.h>

int main() {

    FILE* fptr;   //- File pointer

    //- Get the data to be written in file
    char data[50] = "Now, the more you sweat here,"
                    "\nthe less you'll bleed in battle.";

    //- fopen() is to open an existing file or to create a new one
    fptr = fopen("outputw.txt", "w");    // access mode "w" is to write

    if (fptr == NULL)  //- Checking if the file is created
        printf("The file is not opened.");
    else{
        printf("The file is now opened.\n");
        //- Writing data to file
        fputs(data, fptr);
        fputs("\n", fptr);

        fclose(fptr);  //- if file is open must be closed with fclose()
        printf("Data successfully written in file "
               "outputw.txt\n");
        printf("The file is now closed.");
    }
    return 0;
}
//---

Terminal:

$ gcc test2w.c -o test2w
$ ./test2w
The file is now opened.
Data successfully written in file outputw.txt
The file is now closed.
$

In outputw.txt:

Now, the more you sweat here,
the less you'll bleed in battle.

Well, everything works. But we are here to get data from command line and write it to file, so:

//--
//c
//test2w.c
#include <stdio.h>

int main(int argc, char *argv[])
{
    char *path = (argc > 2) ? argv[2] : "outputw.txt"; // if argv[2] is not indicated get outputw.txt for default

    FILE *fptr = fopen(path, "w");

    if (!fptr) 
    {
        perror("Error creating file ");
        return 1;
    }
    else
    {
        printf("File successfully opened %s\n", path);
    }  

    if (fputs(argv[1], fptr) == EOF)     //- Writes argument to file.
    {
        perror("EOF ");
        return 1;
    }
    else
    {
        printf("Data successfully written in file %s\n", path);
    }    

    if (fclose(fptr))  //- Close file
    {
        perror(path);
        return 1;
    }
    else
    {
        printf("The file is now closed.\n");
    }
    return 0;
}
//--

The code above is thought differently and interesting to study. Output:

$ gcc test2w.c -o test2w
$ ./test2w argonauts outputw.txt 
File successfully opened outputw.txt
Data successfully written in file outputw.txt
The file is now closed.

File outputw.txt:

argonauts

Here too everything works but not well. Both programs writes the given text, replacing any previous contents of the file. It’s not good.

Next article we’ll see how to solve this problem.

Thanks to be here and for having read my article. I’ll be back soon.

There are so many pages online about this topic, here some references: [**1] , [[2](https://www.geeksforgeeks.org/c/basics-file-handling-c/)] and [[3](https://riptutorial.com/c/example/3468/open-and-write-to-file)**]


메타데이터
post_id
6ff56dd03280
slug
easy-way-to-read-input-in-c-and-c-part-5-6ff56dd03280
url
https://medium.com/@doritasci/easy-way-to-read-input-in-c-and-c-part-5-6ff56dd03280
canonical_url
https://medium.com/@doritasci/easy-way-to-read-input-in-c-and-c-part-5-6ff56dd03280
author_url
https://medium.com/@doritasci
status
ok
fetched_at
2026-07-18 17:08:22