I'm at the point of learning how to write to a file. I created these lines as a test.
My concern is that it doesn't look right that I have to write the same sentences for displaying it to screen and to put it in file.
/*
* data.c
* test opening and appending to
* a file.
*/
#include <stdio.h>
int read_int(int *result);
char *read_string(char *string, int size);
int main(void)
{
int n1, n2;
char name[20];
FILE *file_ptr;
file_ptr = fopen("data.txt", "a");
if(!file_ptr)
{
printf("Error opening file");
return(1);
}
else
{
fprintf(file_ptr,"What's your name?: ");
fprintf(stdout,"What's your name?: ");
read_string(name, sizeof name / sizeof *name);
fprintf(file_ptr,"%s\n", name);
}
printf("Enter value for first number: ");
fflush(stdout);
read_int(&n1);
printf("Enter value for second number: ");
fflush(stdout);
read_int(&n2);
fprintf(file_ptr,"n1 = %d\nn2 = %d\n", n1, n2);
fclose(file_ptr);
system("PAUSE");
return(0);
}
int read_int(int *result)
{
char ch, buffer[13];
return fgets(buffer, sizeof buffer, stdin) && !isspace(*buffer) &&
sscanf(buffer, "%d%c", result, &ch) == 2 && (ch == '\0' || ch == '\n');
}
char *read_string(char *string, int size)
{
if(fgets(string, size, stdin) != NULL)
{
int len = strlen(string)-1;
if(string[len] == '\n')
{
string[len] = '\0';
}
else
{
int ch;
do
{
ch = getchar();
}
while(ch != '\n' && ch != EOF);
}
}
return string;
}
fprintf(file_ptr,"What's your name?: ");
fprintf(stdout,"What's your name?: ");
Is there another better way of doing this so I don't have to repeat so much code every time?.