-2

Writing the key value to the file is making the program crash. I know this because I substituted the key value for a normal String and the program worked fine. Why is the key value making the program crash?

#include <stdio.h>
#include <conio.h>

int main() {

  FILE *fp;
  fp = fopen("C:\\Users\\Francisco\\Documents\\C programs\\log.txt", "w");


  int key;

  while(1) {

    if(_kbhit()) {

     key = _getch();

      fprintf(fp, (const char*) key);

    }

  }

  fclose(fp);

  return 0;

}
Lol Lol
  • 155
  • 1
  • 9
  • 1
    In `fprintf(fp, (const char*) key);` you have not provided a format string. Time to read the man page for the `printf` family of functions? The cast may defeat a compiler warning but the `int` will still be treated as an address to be dereferenced. – Weather Vane Jan 22 '19 at 21:12
  • Why would you convert a char (in int form) to a char*? – Phil M Jan 22 '19 at 21:14
  • `fputc(key, fp);` That said, that loop is terrible. It's basically spinning a CPU waiting for a key hit detection. – WhozCraig Jan 22 '19 at 21:23

1 Answers1

1
  fprintf(fp, (const char*) key);

should be

  fprintf(fp,"%c ",key);
Spinkoo
  • 2,080
  • 1
  • 7
  • 23
  • fprintf syntaxe you should provide. the fprintf(the file, the format , and the variable(s)) in my example the file is fp , the format is "%c" which is the character format and then the variable key – Spinkoo Jan 22 '19 at 21:20
  • It is worth pointing out that you are passing `int` for a format specifier which is expecting `char` type to be passed. the reason it works, is because the `char` variable, if passed, would be promoted to `int`, so passing `int` directly does work. – Weather Vane Jan 22 '19 at 21:50