C logging input to file?
I'm working on a program that logs input to a file. This is my current code:
#include <stdio.h>
#include <curses.h>
#include <signal.h>
#define WAIT 3
#define INCORRECT "Incorrect input\n"
#define FILENAME ".xintrc"
int stop();
int main()
{
char first[10], last[10];
int i;
FILE *fp, *fopen()
initscr();
scanf("%[^\n]", first);
getchar();
noecho();
scanf("%[^\n]", last);
printf("\n");
getchar();
echo();
sleep(WAIT);
if((fp = fopen(FILENAME, "a")) != NULL){
fprintf(fp, "First: %s Last: %s\n", first, las开发者_开发问答t);
fclose(fp);
}
printf(INCORRECT);
endwin();
}
stop()
{
endwin();
exit(0);
}
When I compile, I get this error:
input1.c: In function ‘main’:
input1.c:15: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘initscr’
input1.c: In function ‘stop’:
input1.c:35: warning: incompatible implicit declaration of built-in function ‘exit’
Well, you need a semicolon on the end of:
FILE *fp, *fopen(); /* ; here! */
You probably also want stop to match its prototype:
/* includes */
int stop();
/* main etc */
int main(int argc, char** argv)
{
/* main code */
}
int stop()
{
endwin();
exit(0);
}
And for exit()
you need #include <stdlib.h>
Oh and to compile this, let's say it's called test.c
, then use gcc -lcurses test.c -o test
. This tells gcc you want to link with libcurses.
Your code has quite a few problems. See my embedded comments for a version that compiles and presumably does what you want in a more sane manner.
#include <stdio.h>
#include <stdlib.h> /* for _Exit() */
#include <string.h> /* for strcspn() */
/* #include <curses.h> you don't need curses for such a simple program */
/* #include <signal.h> this header is not needed */
#define WAIT 3
#define INCORRECT "Incorrect input\n"
#define FILENAME "testfile"
void stop(void); /* match the new prototype */
int main(void) /* main() always returns int, use void if not using argc/argv */
{
char first[10], last[10];
/* int i; You never use this */
FILE *fp; /* You don't need *fopen() here */
/* initscr(); */
/* noecho(); */
printf("Enter first name: "); /* Added by me */
fgets(first, sizeof(first), stdin); /* Don't use scanf, fgets prevents overflows */
first[strcspn(first,"\n")] = '\0'; /* chomp the newline if it exists */
printf("Enter last name: "); /* Added by me */
fgets(last, sizeof(last), stdin); /* Don't use scanf, fgets prevents overflows */
last[strcspn(last,"\n")] = '\0'; /* chomp the newline if it exists */
/* echo(); */
sleep(WAIT);
if((fp = fopen(FILENAME, "a")) != NULL){
fprintf(fp, "First: %s Last: %s\n", first, last);
fclose(fp);
stop(); /* You never call this, i'm guessing you want it here */
}
printf(INCORRECT); /* only called if fopen() fails */
/* endwin(); */
return 0; /* mandatory return for main() */
}
void stop(void) /* Use 'void' if the func takes no params and returns nothing */
{
/* endwin(); */
_Exit(0); /* _Exit is apart of C99 */
}
精彩评论