Problem with reading and writing to a file at the same time - c

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

Related

trying read and write on the same code in c program

Help I'm trying to write the data in the file. then, trying to read it back, but its not working.
#include <stdio.h>
int main(void) {
FILE *fptr = fopen("try.txt", "r+");
char line[1000];
fprintf(fptr, "i have new number = 1425");
while (fgets(line, 1000, fptr)) {
printf("%s",line);
}
return 0;
}
You must use a positioning function such as rewind() or fseek() between read and write operations.
Beware that the update mode for streams is very confusing and error prone, you should avoid using it and structure your programs accordingly.
Incidentally, your program will fail to open try.txt if it does not already exist, but you do not check for fopen failure so you will get undefined behavior in this case.
Here is a modified version:
#include <stdio.h>
int main(void) {
char line[1000];
FILE *fptr = fopen("try.txt", "w+");
if (fptr != NULL) {
fprintf(fptr, "I have new number = 1425\n");
rewind(fptr);
while (fgets(line, sizeof line, fptr)) {
printf("%s", line);
}
fclose(fptr);
}
return 0;
}

How to allow other sentences to be in a file?

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

the function fgetc is not working properly

i'm testing the fgetc() function but it doesn't work properly (i have used this function befor so i know how it works)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = NULL;
int n;
file = fopen("test.txt", "w+");
if(file != NULL)
{
fputs("ab", file);
printf("%c", fgetc(file));
}
else
{
printf("error");
}
return 0;
}
the output should be "a" but it's somthing else
The file is opened for both writing and reading but you need to fseek to the correct place in the file (here, the beginning). In particular, when switching between writing and reading you need to fseek or fflush.
When the "r+", "w+", or "a+" access type is specified, both reading
and writing are enabled (the file is said to be open for "update").
However, when you switch from reading to writing, the input operation
must encounter an EOF marker. If there is no EOF, you must use an
intervening call to a file positioning function. The file positioning
functions are fsetpos, fseek, and rewind. When you switch from writing
to reading, you must use an intervening call to either fflush or to a
file positioning function.
In any case, after writing to the file, the file pointer is in the wrong place to read what was just written.
So the code becomes
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file = NULL;
file = fopen("test.txt", "w+");
if(file != NULL) {
fputs("ab", file);
fseek(file, 0, SEEK_SET);
printf("%c", fgetc(file));
fclose(file);
}
else {
printf("error");
}
return 0;
}
And if you want to continue writing to the file, you must fseek to its end.
Your error is that you are trying to read a file that has been opened for writting. You should write inside it, then close the file and reopen it for reading. This code will show what I am telling:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fileRead, *fileWrite = NULL;
int n;
fileWrite = fopen("test.txt", "w+");
if(fileWrite != NULL)
{
fputs("ab", fileWrite);
fclose(fileWrite);
}
else
{
printf("error");
}
// Open again the file for read
fileRead = fopen("test.txt", "r");
printf("%c", fgetc(fileRead));
fclose(fileWrite);
// End function
return 0;
}

C - fopen text file after building - OpenWRT - opkg

I have these lines in my C program:
int main(int argc, char **argv) {
int i=0, p=0;
FILE* fp;
fp = fopen("jacina.txt", "w+");
fscanf (fp, "%d", &i);
if (ftruncate(fp, 0) == -1) {
perror("Could not truncate")
};
p = i+10;
fprintf(fp, "%d", p);
}
After building this code to OPKG in OpenWRT (from Ubuntu), how can I read and write to this textual file which is located on any disk location where is located this OPKG?
Your code doesn't make any sense. To write the input given by user to a file:
Create a file first. Take input from user (say any string) and write it to the file with the help of file descriptor (fp) and close the file so that all buffers get flushed.
FILE *fp;
char comment[100] = {0};
fp=fopen("tempfile.txt","w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
printf("Enter String: ");
gets(comment);
fwrite(comment, sizeof(comment), 1, fp) ;
fclose(fp);
fprintf() too can be used instead to write data into a file.
Similarly to read from a file you can use fgets() or fread() to store the contents of the file in a buffer and display the contents of the file. Hope it helps.

Read all Lines of a cpp File with Fgets

in my simple impl. i want to read all lines of a cpp file
FILE * pFile;
fopen_s(&pFile,"test.cpp","r+");
if (pFile!=NULL)
{
fputs ("fopen example", pFile);
char str [200];
while (1) {
if (fgets(str, 200, pFile) == NULL) break;
puts(str);
}
fclose (pFile);
}
my text.cpp contains this:
Testline1
Testline2
Testline3
Testline4
as an output i get unreadable chars:
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
what is wrong with my code?
my idea is to search for a special line of code, and edit it later on
When the file is open for updating, and you want to read2 after writing you need to call fflush1. So call it after you write into the file here:
fputs ("fopen example", pFile);
1 (Quoted from ISO/IEC 9899:201x 7.21.5.3 The fopen function 7)
However, output shall not be directly followed by input without an
intervening call to the fflush function or to a file positioning function (fseek,
fsetpos, or rewind)
2 Output is writing into the file, and input is reading the file.
This code should achieve what you are trying to do:
#include <stdio.h>
#define MAX_LINE 1024
int main(int argc, char *argv[])
{
FILE *pFile;
char buf[MAX_LINE];
fopen_s(&pFile, "test.cpp", "r");
if (pFile == NULL)
{
printf("Could not open file for reading.\n");
return 1;
}
while (fgets(buf, MAX_LINE, pFile))
{
printf("%s", buf);
}
fclose(pFile);
}

Resources