c - 如何在 Unix C 中获取用户输入?

标签 c unix

我正在尝试编写一个可以在 Unix 环境中使用的程序。然而,这是我第一次做这样的事情,我对一些事情感到困惑。我的代码如下:

#include <unistd.h>
#include <stdio.h>

#define BUFFSIZE 4096

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

int n;
char buf[BUFFSIZE];

if (argc != 2){
    err_sys("usage a.out <pathname>");  
}

if (access(argv[1], R_OK) == -1){
    err_ret("access error for %s", argv[1]);
}

if (access(argv[2], R_OK) == 0){
    printf("Would you like to overwrite (Y or N)? \n");
    if(){
        exit(0);
    }
}

while ((n = read(STDIN_FILENO, buf, BUFFSIZE) > 0)){
    if (write(STDOUT_FILENO, buf, n) != n){
        err_sys("write error"); 
    }
}

if (n < 0){
    err_sys("read error");
}

close(STDOUT_FILENO);
close(STDIN_FILENO);

exit(0);

}

好吧,基本上,我必须编写一个使用打开、读取、写入、关闭和访问的程序。但是,如果第二个参数(文件名)已经就位,我对如何实现必须提示用户覆盖或不覆盖的部分感到完全困惑。

又名这些代码行:

if (access(argv[2], R_OK) == 0){
   printf("Would you like to overwrite (Y or N)? \n");
       if(){
           exit(0);
}

我不太确定如何获得用户的响应以及条件是什么。

此外,如果我的其他代码有错误,请随时通知我并让我知道如何改进它。

谢谢!

刚刚添加:

if (open(argv[1], O_RDONLY) < 0){
    err_ret("open error for %s", argv[1]);
}

最佳答案

要只读取一个字符,可以调用 getchar() (stdio.h)(还有 scanf())。

示例:
c = getchar();<br/> if(c == 'Y' || c == 'y'){ ... }<br/> else if(c == 'N' || c == 'n'){ ... }<br/> else { printf("Wrong option!") }<br/>

关于c - 如何在 Unix C 中获取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12344706/

相关文章:

c - 如何仅在配置脚本中启用时使用库

c++ - 为什么即使在包含 math.h 并使用 -lm 链接到数学库之后我仍然得到 "Undefined symbol: .sqrtf"

c - 信号处理函数前 3 次捕获 SIGKILL

c - 为什么建议在打印前将指针转换为通用指针?

c - 当数组在其他文件中且函数在其他文件中时,查找整数或 float 组的大小?

*(unsigned char *)s1 和 (unsigned char)*s1 之间的 C 区别

c - 使用 open()、read() 和 write() 系统调用复制文件

c - 如何在C中获取终端上任何命令的执行文件目录?

linux - 查找文件并以特定格式显示结果到txt文件

java - 使用 Java ProcessBuilder,如何运行位于 UNIX 主目录中的进程?