-2

I am trying to write in a file from a terminal until you write "exit". This code copiles, but doesn't work. It doesn't even write a file ! What should I do?

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);
    }
}

Tanks for your help! :)

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

Here is my solution, tanks to you guys, who reminded me a lot ;)

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);
}
Nickel
  • 13
  • 4
  • Besides the problem with reading the terminal input which is answered below, there should be no reason to not write the file. Are you sure you are actually calling the `my_script()` function? And with a correct value for `name`? – Veger Feb 14 '14 at 13:29
  • What if you write ` exit` with a space before or after the word – Brandin Feb 14 '14 at 14:16

2 Answers2

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);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • 1
    I'm okay with accepting but an explanation could have been great.. otherwise he's going to copy-paste this and learn nothing. – Marco A. Feb 14 '14 at 14:08
  • Huh level that can be fully understood if you look at the reference. – BLUEPIXY Feb 14 '14 at 14:20
  • Oh well, I suppose it works for the user. +1 by me, I didn't think of the fgets in the first place and unleashed Daniel's hell :) – Marco A. Feb 14 '14 at 14:21
-1

You need a console input function like scanf to read from the standard input and then store the read input into an array or something similar:

#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;
}

in your code

strcmp("/stdin", "exit")

is basically asking

are '/stdin' and 'exit' the same characters?

and the answer will always be the same: no. And the loop will always be entered and never left.

Marco A.
  • 43,032
  • 26
  • 132
  • 246