直接在终端上阅读

时间:2014-02-14 13:13:29

标签: c

我正在尝试从终端写入文件,直到你写“退出”。此代码复制,但不起作用。它甚至没有写文件!我该怎么办?

void            my_script(char* name, t_Option option)
{
  FILE          *file;

  (void)option;
  while (strcmp("/stdin", "exit") != 0)
    {
      file = NULL;
      file = fopen(name,"w");
      fprintf(file, "%s", "Writing in a file !\n");
      fclose(file);
    }
}

坦克为您提供帮助! :)

/ * ** * ** * ** * ** * ** * *** /

这是我的解决方案,坦克给你们,他们提醒了我很多;)

void            my_script(char* name)
{
  FILE          *file;
  char          buff[4096];
  int           len;

  file = NULL;
  len = 0;
  file = fopen(name,"w");
  while ((len = read(0, buff, 4096)) != -1)
    {
      buff[len] = '\0';
      if (strncmp(buff, "exit", 4) == 0)
        break;
      fprintf(file, "%s", buff);
    }
  fclose(file);
}

2 个答案:

答案 0 :(得分:1)

FILE *file = fopen(name, "w");
char buff[BUFSIZ];
while(fgets(buff, sizeof(buff), stdin) && strcmp(buff, "exit\n")){
    fprintf(file, "%s", buff);
}
fclose(file);

答案 1 :(得分:-1)

您需要一个控制台输入功能,如scanf从标准输入读取,然后将读取输入存储到数组或类似的东西:

#include <stdio.h>

int main(int argc, char* argv[])
{
  char text[100];   
  do {
    printf("Enter text : \n");                              
    scanf_s("%s", text, 100);
  } while(strcmp(text, "exit"));

  return 0;
}

代码

strcmp("/stdin", "exit")

基本上是在询问

  

是'/ stdin'和'退出'相同的字符?

答案总是一样的:不。循环将始终输入,永远不会离开。