首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将字符串与EOF进行比较?

如何将字符串与EOF进行比较?
EN

Stack Overflow用户
提问于 2016-04-15 12:58:49
回答 1查看 11.2K关注 0票数 1

我已经创建了一个像unix-shell的程序。也就是说,如果键入类似于"./helloWorld“的内容,它将执行程序,然后等待额外的输入。如果输入为EOF (Ctrl + D),则程序必须终止。

我正在努力比较输入,而不使用getchar()或任何需要额外输入的方法。

这是我的密码:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<unistd.h> /* for fork() */
#include<sys/types.h> /* for pid_t */
#include<sys/wait.h> /* fpr wait() */

int main(int argc, char* argv[])
{   
    pid_t pid,waitPid;
    int status;
    char fileName[256];
    while(!feof(stdin))
    {
    printf(" %s > ", argv[0]);
    if (fgets(fileName, sizeof(fileName), stdin) != 0)
    {
        fileName[strcspn(fileName, "\n")] = '\0'; //strcspn = calculates the length of the initial fileName segment, which  consists of chars not in str2("\n")

    char *args[129];
    char **argv = args;
    char *cmd = fileName;
    const char *whisp = " \t\f\r\b\n";
    char *token;
    while ((token = strtok(cmd,whisp)) != 0) // strtok = breaks string into a series of tokens using the delimeter delim(whisp)
    {
        *argv++ = token;
        cmd = 0;
    }// /while

    if (getchar() == EOF)
    {
    break;
    }

    *argv = 0;

    pid = fork();
    if (pid == 0){
    execv(args[0], args);
    fprintf(stderr, "Oops! \n");
    } // /if
    waitPid = wait(&status);



}// /if(fgets..)
} // /while
return 1;

}

我想换掉

代码语言:javascript
复制
if (getchar() == EOF)
        {
        break;
        }

直接比较。类似: if (fileName == EOF) {==;}

这有可能吗?我试过演员和其他方法,但到目前为止都没有效果。有什么不同的方法我没想过吗?更清楚的是,我想知道我的想法是否可行,以及它是否是如何实现的。如果不是,我如何能够终止我的程序与CTRL +D和没有额外的输入。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-15 13:16:34

没有办法将字符串与EOF进行比较;它不是一个char值,而是流上的一个条件(这里是stdin)。但是,如果到达文件结束或出现错误,getchar()getchar()将返回unsigned char强制转换为intint的读char值。

fgets的手册页说:

fgets(s, size, stream)在成功时返回s,在没有读取字符的情况下在文件结束时返回错误的NULL或。

在从NULL获得fgets后,您可以使用feof(stdin)来测试是否已到达文件末尾;或者是否由于错误;同样,您应该能够在使用fgets读取每一行之后检查返回值feof(stdin)。如果feof(stdin)返回0,则尚未到达文件结束;如果返回值为非零,则意味着达到了EOF。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36647846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档