How to keep the data in file.txt? - c

I want to store the data in file.txt even if I run the code again. Whenever I run the code it removes all the previous data.
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
FILE *fptr = fopen("file.txt", "w");
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}

Open the file in "append" mode:
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
FILE *fptr = fopen("file.txt", "a"); /* <===== changed from "w" to "a" */
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}
New data will now be added at the end of the file.

Related

The system cannot find the path specified error when doing file related operations

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *fptr;
char path[150];
char content[2000];
char file[50];
puts("Enter the path of the file");
scanf("%s",path);
fptr = fopen(path,"w");
//fptr = fopen("C:\\Users\\dell_latitude_3490\\Documents\\Hello.txt","w");
if(fptr==NULL){
printf("Error");
exit(1);
}
printf("Enter a sentence:\n");
fgets(content, sizeof(content), stdin);
fprintf(fptr, "%s", content);
fclose(fptr);
printf("Content Successfully added to File");
return 0;
}
I don't get error when specifying:
fptr = fopen("C:\Users\dell_latitude_3490\Documents\Hello.txt","w");
But I get error when reading the path from user and specifying:
fptr = fopen(path,"w");
Someone help me resolve this...

How to print the text from a file if the line number is given?

I want to give input as line number and get output as the corresponding text for that line number in a text file.
Sample text file:
Hi this is Stefen
Hi How are you
Example input:
Enter the line number:2
Expected Output:
Hi How are you
My program is:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("sample.txt", "r");
if (fp == NULL) {
perror("Unable to open the file\n");
exit(1);
}
char buf[256];
while (fgets(buf, sizeof(buf), fp) != NULL) {
printf("%s\n", buf);
print("~~~~\n");
}
fclose(fp);
return 0;
}
Output I got:(The entire file with the separator ~~~~ below each line)
Hi this is Stefen
~~~~
Hi How are you
~~~~
Can anyone please tell me how to do this?
As pmg suggests, would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define INFILE "sample.txt"
int main()
{
FILE *fp;
char buf[BUFSIZ];
int count = 0, n;
fp = fopen(INFILE, "r");
if (fp == NULL) {
perror(INFILE);
exit(1);
}
printf("Enter the line number: ");
fgets(buf, sizeof buf, stdin);
n = (int)strtol(buf, (char **)NULL, 10);
while (fgets(buf, sizeof buf , fp) != NULL){
if (++count == n) {
printf("%s", buf);
break;
}
}
fclose(fp);
return EXIT_SUCCESS;
}
Best to use a second file
check if you're at \n that means new line and increment a variable like "line"
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
ptr2 = fopen("c:\\CTEMP\\newfile.txt", "w");
if(ptr2==NULL)
printf("second error opening newfile");
while (!feof(ptr1))
{
ch = fgetc(ptr1);
if (ch == '\n')
{
temp++;
}
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file newfile.c
fputc(ch, ptr2);
}
}
fclose(ptr1);
fclose(ptr2);
"detele_line" variable is for the user to inter.
The easiest way is using array to save the lines, then print the certain line.
#include <stdio.h>
#define M 10010
#define N 256
char buf[M][N];
int main(){
FILE *file;
char fileName[50] = "sample.txt";
file = fopen(fileName, "r");
if(file == NULL)
return 1;
int n = 0;
while(fgets(buf[n], N, file) != NULL){
n++;
}
fclose(file);
int i, x;
printf("Example input:\nEnter the line number:");
scanf("%d", &x);
printf("Expected Output:\n%s", buf[x-1]);
return 0;
}

How to store string to txt file

void inserting()
{
char file_name[50];
char sentence[1000];
FILE *fptr;
printf("File name (With extn):");
scanf("%s", file_name);
fptr = fopen(file_name, "a");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%s", sentence);
fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
I want to store content from string to file... but it is displaying everything except the first word..
INPUT : Hello this is C program //which I have entered
OUTPUT: this is C program //this is what stored in file
#include<stdio.h>
void inserting()
{
char file_name[50]="C:\\Users\\Dev Parzival\\Desktop\\foo.txt";
char sentence[1000];
FILE *fptr;
//printf("File name (With extn):");
//scanf("%s", file_name);
fptr = fopen(file_name, "w");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%[^\n]", sentence);
printf(sentence);
//fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
int main(){
inserting();
}
scan will not read spaces with%s u have to include spaces also I assume thats why use %[^\n]format specifier.
If you want to preserve your code make the adjustment
void inserting(){
char file_name[50];
char sentence[1000];
FILE *fptr;
printf("File name (With extn):");
scanf("%s", file_name);
fptr = fopen(file_name, "a");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%s", sentence);
fprintf(fptr,"%s",sentence); //<-- HERE
fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
Or you can use something like getline just to be cleaner.

How to scan a string and write it in a file?

I want to scan a string that a user inputs, then write it into the file (file.txt), but this doesn't seem to work for some reason
int main()
{
FILE *stream;
stream = fopen("file.txt", "w");
char str[] = { '\0 ' };
scanf("%s", &str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return(0);
}
try this, should work just fine.
It did for me so it should for you too.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *stream;
stream = fopen("ceva.txt", "w");
if (stream == NULL) {
perror("Failed: ");
return 1;
}
char str[250];
scanf("%249s", str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return 0;}
You must change scanf with fscanf

Read from file in C and execute conditional logic

I am new to programming and have a few questions as to how to implement this idea.
I am looking to have a user enter their name/string of digits and if their name is on a list, to then execute a string of commands. I am not to sure how to impliment this, but with some gogle-ing I was able to come up with this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char userName[10];
printf("\n\n\n\nPlease enter your name: ");
scanf_s("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
if (fp == John) {
//Dispence squence of pills for John
}
if (fp == Mary) {
//Dispence squence of pills for Mary
}
return 0;
}
I do not think I am using the if statement correctly. how can I do something like:
if (content in fp == john, execute/call another function)
Thanks in advance!
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char userName[10];
char names[20];
printf("\n\n\n\nPlease enter your name: ");
scanf("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
while(fgets(names, 20, fp)) // fgets reads a line from the file
{
names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
{
printf("Match found\n");
}
}
return 0;
}
fopen simply opens a file for reading and/or writing, to read the actual content of the file you need to use functions such as fgets, fscanf and so on.
Short example
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
char name[64];
char buffer[64];
printf ("Please enter your name: ");
file = fopen ("results.dat", "rw");
if (!file) {
printf ("Results.dat could not be opened.\n");
exit(-1);
}
if ( fgets (buffer, 64, file)) {
if (strcmp (buffer, "john")) {
printf ("Contents of file is john\n");
}
}
return 0;
}

Resources