简体   繁体   中英

How to input a text file into an exe through cmd?

Trying to use my program to take a stdin through the cmd .

For example, I have a program that takes in a number from user input using scanf.

How do I use the console to redirect the input.

I've tried program.exe < input.txt , but I get an error that the file specified is not found.

When I run the exe and type <input.txt , it outputs a single line of what I assume to be a memory address.

edit: Figured out the input, however getting an unexpected output.

 #define SIZE 5
    int main(){

    int i,j,num, row[SIZE];
    char line[SIZE+1];


    scanf("%d", &num);
    printf("%d", num);

    for(i=0;i<num;i++){

        scanf("%s", line);

        for (i=0; i<SIZE; i++)

             arr[i] = line[i] - '0';

        printf("%d",arr);

What it's meant to do is take in a number of lines to variable num.

From there, it should can the all lines and take a string of numbers, then put that string of numbers into an array of int.

Eg input

1
28374

eg output

28374

Which should really be

arr[0]=2, arr[1]=8, arr[2]=3,
and so on

.

1) Using command line argument pass file name to your c program. study this http://www.tutorialspoint.com/cprogramming/c_command_line_arguments.htm

2) then in your c program open that file and read input.

It goes like this:

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

#define BUFFER_SIZE 256

int main ()
{
    int16_t i;                                                                                                                                                         
    char buffer[BUFFER_SIZE];

    while (NULL != fgets(buffer, sizeof(buffer), stdin)) {
        sscanf(buffer, "%[^\n]", buffer);

        uint8_t len = strlen(buffer);
        uint8_t numbers[BUFFER_SIZE] = {0};

        for (i = 0; i < len; i++) {
            numbers[len - 1 - i] = buffer[i] - '0';
        }

        bool high = false;
        for (i = BUFFER_SIZE - 1; i >= 0; i--) {
            high = high || (0 != numbers[i]);

            if (high) {
                printf("[%d] => %d\t", i, numbers[i]);
            }
        }

        putchar('\n');
    }   

    return EXIT_SUCCESS;
}

content of input numbers.txt :

54673
1245841
326987

Then you can run your program like this:

./app < numbers.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM