| | |
Appending to a text file
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
![]() |
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.
Is there another better way of doing this so I don't have to repeat so much code every time?.
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.
c Syntax (Toggle Plain Text)
/* * 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?: ");
"If it moves, tax it. If it keeps moving, regulate it, and if it stops moving, subsidize it" - Ronald Reagan
You asked this question already.
What you should do is create a function that does the screen and file printing; all you have to do is pass the string and the file as arguments.
I was thinking something like this:
Note that this fprintf() wrapper is not nearly as robust as the fprintf() function; it certainly doesn't accept any extra parameters. However, this should help to reduce the bulk of your code by a bit.
Additionally, do not forgot to flush the streams, either in this function, or in the main() function like you were already doing.
What you should do is create a function that does the screen and file printing; all you have to do is pass the string and the file as arguments.
I was thinking something like this:
C Syntax (Toggle Plain Text)
void printToFileAndScreen(FILE *filePtr, char *myString) { if (myString) { fprintf(stdout, myString); fprintf(filePtr, myString); } }
Note that this fprintf() wrapper is not nearly as robust as the fprintf() function; it certainly doesn't accept any extra parameters. However, this should help to reduce the bulk of your code by a bit.
Additionally, do not forgot to flush the streams, either in this function, or in the main() function like you were already doing.
"Technological progress is like an axe in the hands of a pathological criminal."
All my posts may be freely redistributed under the terms of the MIT license.
All my posts may be freely redistributed under the terms of the MIT license.
Yes, I asked a question related to this topic, and this piece of code is the result of what I understood from you and some more reading.
Sorry, I didn't want to bother you. I didn't want you to write me a function, I just wanted confirmation that what I was understanding is correct code.
Sorry, I didn't want to bother you. I didn't want you to write me a function, I just wanted confirmation that what I was understanding is correct code.
"If it moves, tax it. If it keeps moving, regulate it, and if it stops moving, subsidize it" - Ronald Reagan
•
•
•
•
Sorry, I didn't want to bother you. I didn't want you to write me a function, I just wanted confirmation that what I was understanding is correct code.

Anyway, you have to keep several things in mind with C/C++: Don't assume anything. If it doesn't look like it's going to do something, don't assume it does. An example of this is memory management. Well, actually C takes care of any statically allocated variables, but as soon as you start using dynamic memory... you're on your own!
What does this mean for you? It usually means that there's no easy prewritten function for any semi-complex task you want to accomplish. Most often you have to implement it yourself, as is the case here.
"Technological progress is like an axe in the hands of a pathological criminal."
All my posts may be freely redistributed under the terms of the MIT license.
All my posts may be freely redistributed under the terms of the MIT license.
![]() |
Similar Threads
- connect to text file database (Visual Basic 4 / 5 / 6)
- Output in the text file (C)
- Create stats from a text file (Java)
- Store Bluetooth remote address to a text file (C++)
- 10 line text file (Java)
- Read and write to an ASCII Text file (Java)
Other Threads in the C Forum
- Previous Thread: function calling problem
- Next Thread: turning userinput into a text file
Views: 3281 | Replies: 3
| Thread Tools | Search this Thread |
Tag cloud for C
adobe ansi api array arrays bash binarysearch centimeter char convert copyanyfile copypdffile cprogramme createcopyoffile createprocess() csyntax directory drawing dynamic executable fflush file fork frequency getlasterror givemetehcodez global graphics gtkgcurlcompiling hardware highest homework i/o inches infiniteloop initialization interest km lazy linked linkedlist linux linuxsegmentationfault list locate logical_drives match matrix meter microsoft motherboard multi mysql open opendocumentformat opensource openwebfoundation owf pattern pdf performance pointer pointers posix power problem probleminc program programming pyramidusingturboccodes read recursion recv repetition scanf scheduling segmentationfault send shape socketprograming spoonfeeding stack standard strchr string strings structures student suggestions system systemcall test testautomation unix user voidmain() wab win32 win32api windows.h






