How to add multiple lines in text file - c

I am trying to write a program which can display the contents of the file then append the content dynamically by user to a text file in C.
Below is the code, but somehow it is working for single line input and not for multi-line input even in the loop.
fobj=fopen("test3.txt","a");
if (fobj==NULL)
{
printf("Error opening the file. ");
exit(0);
}
int contd;
char buff1[120];
char *chptr;
do
{
printf("Enter line : \n");
gets(buff1);
fputs(buff1,fobj);
printf("Enter Continuation code : ");
scanf("%d",&contd);
}while(contd!=0);

You are facing the typical stdin issue. You can use fflush(stdin); before gets, should work.

From gets:
The newline character, if found, is not copied into str.
So you will have to add the new line manually:
gets(buff1);
strcat(buff1, "\n");

Related

fopen with string variable fails

I'm trying to make a small program that saves some information on a file, taking input from the user for the content and name of the file. For some reason, I am unable to save file_name into FILE *open.
This works when input a string as the file name; open = fopen("filename.txt","w"); but not when I try to input string as a variable. I have looked all over and cannot find an answer anywhere.
I have included stdio.h and string.h
int main (){
FILE *open;
char first_name[16],last_name[21];
char save_name[30],ext[10];
char file_name[40];
int a,b;
printf("This program will take your name and save it in a file.\n");
printf("Insert your first name:");
scanf("%s",&first_name);
printf("Insert your last name:");
scanf("%s",&last_name);
do{
printf("Insert file name with extension:");
scanf("%[^.].%s", &save_name, &ext);
//Takes filename lenght, minus the dot
a = (int)strlen(save_name)-1;
b = (int)strlen(ext);
sprintf(file_name,"%s.%s",save_name,ext);
}while(a>8 || b>3);
//This is where my problem lies...
open = fopen(file_name,"w");
if(open==NULL){
printf("File %s failed to open, shutting down...",file_name);
}
else{
fprintf(open, "%s %s",first_name,last_name);
printf("\n\nSave successful! File was saved as: %s",file_name);
}
fclose(open);
return 0;
}
The problem is that your file_name has a leading newline character in it! The newline is being added by your scanf() call with the "%[^.]" format (but I'm not entirely sure why). It seems that using %s for string input automatically removes this but %[^.] will accept all characters except . (including whitespace). Use this to fix it (skipping the newline):
scanf("\n%[^.].%s", &save_name, &ext);
Comments welcome as to where this newline comes from - it's news to me!
PS: You don't need the - 1 in your calculation of a, as the dot is never read into save_name.

fgets function and file handling in C

I am trying to make a program which will store the data entered by the user in a text file whose name is provided by the user. Program will terminate when the user enters exit. strcmp function of string.h is used for string comparison and fgets() is used to read data from stdin.
Here is my code.
#include<stdio.h>
#include<string.h>
void main()
{
char file[60]; // will store file name
printf("Enter file name: ");
fgets(file, 59, stdin);
FILE *fp = fopen(file, "a+"); // open file in append mode
if(fp == NULL){
printf("File not found !");
return;
}
char data[100];
printf("Enter some data to add to file(exit to terminate): ");
fgets(data, 99, stdin);
int flag = strcmp(data, "exit");
while(flag != 0){
fputs(data, fp);
fgets(data, 59, stdin);
flag = strcmp(data, "exit");
printf("%d\n", flag); // for checking whether string are correctly comapred or not
}
printf("Bye");
}
Program does not terminate even if i enter exit. I have also tried concatenating "\n" at the end of string input by user but that also doesn't help. Although, gets() function works fine, but i know it is not preferred to use to I shifted to fgets() but it doesn't work for me.
Check the man page for fgets(), it reads and stores the newline (caused by pressing ENTER) after the entered input. Thus, the strcmp() fails.
You have to manually strip the input buffer off the newline, before you can compare the input. A simple yet elegant way of doing that would be
data[strcspn(data, "\n")] = 0;
fgets reads in a complete "line", i.e. a sequence of characters until (and including!) a new line character. Hence, when a user presses "Enter", the new line will be part of the string read in and a strcmp(data,"exit") will evaluate to "not equal".
So either strip off the new line before comparison, or compare with a string literal including a new line. Since you write the data as is(i.e. including the new lines) to a file, it seems cumbersome to first strip the new line off and add it then in the output manually. So I'd actually suggest the second approach:
fgets(data, 100, stdin);
flag = strcmp(data, "exit\n");
An alternative would be to use strstr if excess characters do not matter (i.e. your program would exit if the user types "exit" or "asdfexitasdf". - both of which contain "exit".)
So
int flag = strstr(data, "exit");
if(flag != NULL)
//exit the program
else
//stay in the program

Check if the user input an empty string in C using char array

I'm trying to have the program check, that, if a user inputs nothing the print statement will say it cant find the file name, but the issue I'm having is that the command line will just go to a new line after hitting enter instead of saying the print statement.
This is the code here. I was told that Null is the place holder for if nothing is put in so I thought it would work.
int main()
{
FILE *fin;
FILE *fout;
char fInName[50];
char fOutName[50];
printf("pleas type input file, and output file please type legibly\n ");
scanf("%s %s", &fInName, &fOutName);
fin = fopen(fInName, "r");
fout = fopen(fOutName, "r");
if (fInName == NULL && fOutName == NULL)
{
printf("Error: Cannot open input file %s.", fInName);
}
else if (fInName != NULL && fOutName == NULL)
{
printf("file found");
}
}
What im trying to test is if a first file name is entered and the second isnt then print the statement. If both arent entered then print file does not exist.
there is more to the code to see if the file exists or not, but thst would be a bit much, now Im just trying to understand why it wont read unentered data.
Ive tried looking at examples such as: How to detect empty string from fgets
and tried to alter the code to fit that type of style but it didnt work for me so Im giving you the code it was originally so that anything helpful wouldnt confuse me more.
Edit:
okay so I tried to do a simple code in order to see what may be the cause of this issue:
int main()
{
char firstname[50];
char lastname[50];
char nothing [0];
printf("pleas type input file, and output file please type legibly pwease\n ");
scanf("%s" "%s", firstname, lastname);
if (firstname == lastname )
{
printf("Error: Cannot open input file %s.", firstname);
}
else
{
printf("file found");
}
}
I ran the code using adam and either if I typed adam (space) adam or adam(enter) adam the program thinks that the input is not the same, I feel like that would help identify why it doesnt know why nothing is typed in.
The problem is occurring when you try to check if fInName == NULL.
The problem is that fInName is just a variable that you're using to store the name of the file that you want to open. What you actually want to check is that the user gave you a valid filename, and to do so you will want to understand what the return value of functions are.
For example, when you try to open a file using fopen(), if fopen() is unable to successfully open the file, say because the user didn't input anything or misspelled the filename, then fopen() will return NULL, storing it in whatever variable you assigned it to (in your case, *fin and *fout).
Also, scanf() is not recommended for char arrays because if the user inputs more data than you allocated for the array, which in this case is enough space for 50 characters, then scanf() will try to write data to memory that's not yours, causing a buffer overflow.
A much safer option is to use fgets() because you can choose exactly how much data is written into your char array, with the only downside being that fgets() will write newline characters \n (caused by hitting the enter key) into the array, though the simple solution is to overwrite the newline character with '\0'.
Therefore, I would propose:
int main(void)
{
char fInName[50];
char fOutName[50];
// ensure proper usage
do
{
printf("What file would you like to open? ");
// get infile from user and remove trailing newline '\n' character
fgets(fInName, 50, stdin);
fInName[strcspn(fInName, "\n")] = '\0';
}
// prompt for input until user enters something
while (strlen(fInName) < 1);
do
{
printf("What file would you like to output to? ");
// get outfile from user and remove trailing newline '\n' character
fgets(fOutName, 50, stdin);
fOutName[strcspn(fOutName, "\n")] = '\0';
}
// prompt for input until user enters something
while (strlen(fOutName) < 1);
FILE *fin = fopen(fInName, "r");
if (fin == NULL)
{
printf("Error: Cannot open input file %s.", fInName);
return 1;
}
else
{
printf("file found");
}
}

Reading whitespace when asking user input C

I'm having issues trying to read a white space character in C. What I want to do is read user input when asking for a first and last name.
So for example, I prompt the user to enter their name, they type in something like "Peter Smith". With that info, I want to write it to a file.
When it writes it to a file, the file only reads the last name "Smith". How can I read the whole string?
Here's how I asked:
printf("\nPlease enter your first and last name: \n");
scanf("%[^\n]", name);
fgets(name, sizeof(name), stdin);
I don't think your problem lies in the snippet you posted. Here's an example program I wrote on my Linux system to try and pinpoint the issue:
#include <stdio.h>
int main()
{
char name[128];
int num_scans = 0;
FILE *out = fopen("name.txt", "w");
if(out == NULL)
{
printf("Failed to open file for write.\n");
return 1;
}
printf("\nPlease enter your first and last name: \n");
num_scans = scanf("%127[^\n]", name);
if(num_scans < 1)
{
printf("Error reading name.\n");
return 2;
}
fprintf(out, "%s\n", name);
fclose(out);
return 0;
}
This appeared to work for me:
$cat name.txt
Peter Smith
If you post the code you used to write the name to a file, that might reveal the source of the error.
The code is working correctly. The fgets call replaces the value you read for the first name.
You should stick to one scheme of input. When you switch between input paradigms "strange" things happen. (Technically they are exactly what is supposed to happen, but typical users tend to not be too precise about exactly how each function works, and what state the input stream is left in.)

Reading and Displaying content of the Text File via C coding

I am trying to code a game in C that deals with selection of races.
Each races has their own "stories" and when the user chooses to read one of their stories,
what I want to happen is,
While the program is running on Command Prompt, it will display the content I have typed in that specific text file about the story of the selected race.
This is what I have done so far.
void Race(char nameRace[20])
{
int race_choice,race_choice2,race_story;
FILE *race;
FILE *race1;
FILE *race2;
FILE *race3;
printf("The Races: 1.Human 2.Elf 3.Orc\n");
printf("Press 1 for Details of Each Races or 2 for selection: ");
scanf("%d",&race_choice);
if (race_choice==1)
{
printf("Which Race do you wish to know about?\n\t1.The Human\n\t2.The Elf\n\t3.The Orc\n\t: ");
scanf("%d",&race_story);
if (race_story==1)
{
race1=fopen("race1.txt","r");
fgetc(race1); // This does not display what I have typed on the race1.txt file on Command prompt.
// And I plan to write 2~3 paragraphs on the race1.txt file.
printf("\nGo Back to the Selection?(1 to Proceed)\n ");
scanf("%d",&race_choice2);
if (race_choice2==1)
{
printf("\n\n");
Race(nameRace);
}
else
{
wrongInput(race_choice2);// This is part of the entire code I have created. This works perfectly.
}
}
}
}
Please help me? :) Please!
The functionality you seem to be lacking is the ability to read a text file and output it. So it might be a good idea to code up a function which does just this, and then you whenever you need to display the contents of a file you can just pass a file name to our function and let it take care of the work, e.g.
static void display_file(const char *file_name)
{
FILE *f = fopen(file_name, "r"); // open the specified file
if (f != NULL)
{
INT c;
while ((c = fgetc(f)) != EOF) // read character from file until EOF
{
putchar(c); // output character
}
fclose(f);
}
}
and then within your code would just call this as e.g.
display_file("orcs.txt");
fgetc function reads, and returns single character from file, it doesn't prints it.
So you will need to do following:
while(!feof(race1)) { // Following code will be executed until end of file is reached
char c = fgetc(race1); // Get char from file
printf("%c",c); // Print it
}
It will print contents of race1 char-by-char.
I think you'll probably want to read the file line by line, so it's best to use fgets() instead of fgetc().
Example:
while(!feof(race1)) // checks to see if end of file has been reached for race1
{
char line[255]; // temporarily store line from text file here
fgets(line,255,race1); // get string from race1 and store it in line, max 255 chars
printf("%s",line); // print the line from the text file to the screen.
}
If you replace fgetc(race1) with the chunk of code above, it may work. I have not tried running it but it should work.

Resources