C - If (No File Found) { 使用标准输入 }

标签 c file input stdin

我有一个从文件中读取的程序,但是如果参数数组中没有声明文件,那么我想从终端的标准输入中读取例如:

 ./program.out test.txt

从 test.txt 读取

 ./program.out

从标准输入读取:

这是我的一些上下文代码:

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

FILE *fr;
char *line;
char *word;
size_t len =256;
int i=0;
int sum=0;
char *vali;
const char delim = ' ';
int flag=0;

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

line = (char *)malloc(len);
word = (char *)malloc(len);


/*
line = (char *)malloc(sizeof(&len));
word = (char *)malloc(sizeof(&len));
vali = (char *)malloc(sizeof(&len));
*/
    fr = fopen(argv[1], "r");
    if(fr==NULL){
        //fr="/dev/stdin"; <-- Piece of code I need for this stackoverflow question
    }

        while (getline(&line, &len, fr) != -1){
            /* printf("%s", line ); */
            if(strlen(line) != 1){
                sscanf(line,"%s%*[^\n]",word);
                 printf("%-10s ", word); 
                char *scores = line + strlen(word) + 1;         
    /*          printf("scores: %s", scores); */



                vali=strtok(scores, &delim);
                while(vali != NULL){
                    sum=sum+atoi(vali);

                    vali = strtok(NULL, &delim);
                }

                printf("%3d\n", sum);
                sum=0;
            }
        }
        fclose(fr);

    free(line);
//   free(word);
//  free(vali);
    return 0;
}

最佳答案

更改这些行:

fr = fopen(argv[1], "r");
if(fr==NULL){
    //fr="/dev/stdin"; <-- Piece of code I need for this stackoverflow question
}

if ( argc > 1 )
{
    // A file was passed in as the first argument.
    // Try to open it.
    fr = fopen(argv[1], "r");
    if(fr==NULL){
       // Deal with the error of not being able to open the file.
    }
}
else
{
    // Nothing was passed to the program.
    // use stdin.
    fr = stdin;
}

关于C - If (No File Found) { 使用标准输入 },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204792/

相关文章:

python - 用元组替换程序中的列表?

java - 试图比较两个迭代器的内容,怎么样?

c - 在 printf 语句中使用 *

python - 是否有一个统一的python库来使用不同的协议(protocol)传输文件

android - 无法在外部存储中创建新文件路径

java - 如何在java中找到非常大的文件复制状态

javascript - 数字输入不会将 0 作为 React 应用程序中的值

java - Java 谓词的 C/C++ 等价物

c - 如何在不更改初始 token 的情况下存储 strtok 的临时值

c - 链表不打印?