In this code whenever I write a new sentence, it replaces the previous sentence in a file that I put earlier. I want to not replace the previous sentence and also allow other sentences in that file line after line.
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
// creating file pointer to work with files
FILE *fptr;
// opening file in writing mode
fptr = fopen("file.txt", "w");
// exiting program
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.
fptr = fopen("file.txt", "a");
https://en.cppreference.com/w/c/io/fopen
Related
I'm trying to read a text file that will contain two lines, something like this:
18,3,4,c;19,3,5,D
19100,18,18;19102,3,2
and i want to store the first line in a string called Students and the second one into another string called Courses.
I have wrote this code but it stores one line only and i can't get it to work with the second line
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fscanf(fptr, "%[^\n]", Students);
fclose(fptr);
Can anyone help me with that? I'm a newbie to c and i can't get how to do so, Thank you in advance.
FILE *fptr;
char buffer[255] = {'\0'};
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fgets(Students, sizeof(Students), fptr);
fgets(Courses, sizeof(Courses), fptr);
fclose(fptr);
This line fgets(Students, sizeof(Students), fptr); will start reading from the begginning of the file and store the first line to Students char array & then fgets(Courses, sizeof(Courses), fptr); will read the second line and store it into Courses char array.
Make sure that the size of Students & Courses is large enough to accommodate each line into them.
You may try fscanf() for the problem:
#include <stdio.h>
int main(void) {
char Students[100], Courses[100];
FILE *fp = fopen("program.txt", "r");
if (!fp) {
printf("File wasn't opened.\n");
return -1;
}
fscanf(fp, "%s \n", Students);
fscanf(fp, "%s", Courses);
printf("%s\n", Students);
printf("%s\n", Courses);
fclose(fp);
return 0;
}
My program.txt contains:
John_Doe
Mathematics
Sample Output
John_Doe // Students
Mathematics // Courses
Use something like:
fscanf(fptr, "%[^\n]\n%[^\n]]\n", Students,Courses);
Where you tell scanf() to read up to a new-line, read and discard the new line, then do it again.
I am trying to read and write the file at the same time in C. I can write to the file but couldn't read from the file. Any suggestions?
#include <stdio.h>
int main()
{
char *str = "C programming language";
char str1[100];
FILE *fptr = fopen("Output.txt", "r+");
if (fptr == NULL)
printf("Could not open file!");
fputs(str, fptr);
fgets(str1,100,fptr);
fclose(fptr);
printf("%s", str1);
return 0;
}
Please assume that the output.txt file already exists on my computer.
Quoting http://www.cplusplus.com/reference/cstdio/fopen:
For files open for update (those which include a "+" sign), on which
both input and output operations are allowed, the stream shall be
flushed (fflush) or repositioned (fseek, fsetpos, rewind) before a
reading operation that follows a writing operation. The stream shall
be repositioned (fseek, fsetpos, rewind) before a writing operation
that follows a reading operation (whenever that operation did not
reach the end-of-file).
After you've done the write, you should seek to beginning of the file. For that call rewind().
Here's the corrected code:
#include <stdio.h>
int main()
{
char *str = "C programming language";
char str1[100];
FILE *fptr = fopen("Output.txt", "r+");
if (fptr == NULL)
printf("Could not open file!");
fputs(str, fptr);
rewind(fptr); // seek to beginning
fgets(str1,100,fptr);
fclose(fptr);
printf("%s", str1);
return 0;
}
You will need to re-position the offset to beginning to read that string.
After your write, the pointer is at the offset which is past the string your wrote.
#include <stdio.h>
int main()
{
char *str = "C programming language";
char str1[100];
FILE *fptr = fopen("Output.txt", "r+");
if (fptr == NULL)
printf("Could not open file!");
fputs(str, fptr);
fseek(fptr, 0, SEEK_SET); // add this
fgets(str1,100,fptr);
fclose(fptr);
printf("%s", str1);
return 0;
}
./main.out
C programming language
This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}
I am having problems with copying txt files. I need to info from one file to another.
My code looks like this,
_tprintf (TEXT("%s\n"), FindFileData.cFileName);
memset(fileName, 0x00, sizeof(fileName));
_stprintf(fileName, TEXT("%s\\%s"), path, FindFileData.cFileName); //iegust
FILE *fptr = fopen(fileName, "r");//atver
fscanf(fptr,"%[^\n]",c); //iegust datus no faila
printf("Data from file:\n%s",a);
strcpy(a, c); //nokope datus
buffer2 = strtok (c, ","); //norada partraukumu un tadas lietas
while (buffer2) {
buffer2 = strtok (NULL, ",");
if(i<1){ printf("%s\n", c);}
i++;
while (buffer2 && *buffer2 == '\040'){
buffer2++;
// TODO ieliec iekavinas
}
}
And after that I use basic fputs().
My problem is that this code ignores new lines. It prints out fine, each string in it's own line, but that does not happen in file. (\n).
Your problem is that you just need to copy information from one file to another. So, why you don't use a simple solution to do it than your. I have a snipet code can solve your problem easily as shown below.
If I am wrong about your question, please give me advices.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
How i can make a new line at the end of a file to fprintf() user inputed text?
My code right now is this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int lines;
int number;
FILE *fp;
printf("Insert random number: ");
scanf("%d", &number);
fp = fopen("textfile.txt", "r");
char ch;
while((ch=fgetc(fp))!=EOF)
{
if (ch=='\n') {
lines++;
}
}
fclose(fp);
fopen("textfile.txt", "ab");
fseek(fp, lines, SEEK_SET);
fprintf(fp,"%d", number);
fclose(fp);
}
You just need to add a '\n' to the fprintf() like this
fprintf(fp,"\n%d", number)
/* ^ */
but you also need a lot of error checking, for instance fopen() returns NULL when it fails to open the file.
Your code is actually very broken, you count the lines in the file opened with "r", i.e. for reading, then you call fopen() with "ab" but discard the return value, you then fseek() the number of lines, and fseek() is for the number of characters not lines, then you write to the closed fp pointer, because
fopen("textfile.txt", "ab"); /* you don't assign the return value anywhere */
fseek(fp, lines, SEEK_SET); /* this is the same pointer you `fclosed()' */
/* ^ this will not seek to the end of the file */
fprintf(fp,"%d", number); /* here `fp' is still invalid */
Test this
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
const char *filename = "textfile.txt";
printf("Insert a number: ");
if (scanf("%d", &number) != 1)
{
fpritnf(stderr, "invalid input, expected a number\n");
return -1;
}
file = fopen(filename, "a");
if (file == NULL)
{
fprintf(stderr, "cannot open %s for appending\n", filename);
return -1;
}
fprintf(file, "\n%d", number);
fclose(file);
return 0;
}
You don't need to fseek() if you open with "a" because new content is appended to the end of the file, you need a '\n' before the user input if there was no '\n' in the file or if you want to force the new value in a new line.
You don't need the "b" in the mode string, because you are writing text to the file, and on some platforms the file will have issues when you open it in a text editor.