grinder wrote:
first off, i am an extreme newbie to C. i am an undergrad research
assistant and i have been shifted to a project that involves building a
fairly involved c program. The part that i am stuck on now is as
follows:
- i am trying to write code that will take any number of text inputs
(names of other text files) and put them into a file line-by-line at
the users request. meaning, i want the user to be able to type the
strings and enter them subsequently into a file. this file will then be
read line-by-line by another program which will intern use the lines as
references to data files.
Your description is very unclear. If the input lines are names of other
text files, are we supposed to open those text files and insert the
contents of them into the output file? Or just output exactly what the
user wrote?
so, i am trying to figure out a way to prompt the user to enter the
text(s) one after another and have them store in a file.
Here is a way to prompt the user to enter lines of text, and store what
the user wrote into a file.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* declare an int variable to hold characters */
int ch;
/* open a file for output: */
FILE *fp = fopen("output.txt", "w");
/* check that it opened: */
if(fp == NULL)
{
fprintf(stderr, "Error opening output file\n");
exit(EXIT_FAILURE);
}
/* give instructions to user */
puts(
"Enter your lines of text and they will be written\n"
"into the output.txt file. When you are finished,\n"
"generate an end-of-file condition. On Unix this is\n"
"done by pressing Ctrl-D whereas on Windows/DOS it is\n"
"done by pressing F6 or Ctrl-Z then Enter.\n");
/* read characters from stdin and put them into the file */
while((ch = getchar()) != EOF)
{
if(putc(ch, fp) == EOF)
{
fprintf(stderr, "Error writing to output file\n");
exit(EXIT_FAILURE);
}
}
/* close the file */
if(fclose(fp) == EOF)
{
fprintf(stderr, "Error closing output file\n");
exit(EXIT_FAILURE);
}
return 0;
}
It doesn't actually consider lines of text as such, instead just reading
and writing character by character. Due to the line buffering in most C
implementations you can edit each line as you type it, and it will only
be submitted to the program and written to the file after you press the
Enter key.
--
Simon.