In the file "file1.dat" I wrote "anahasapples". And then I wrote this program:
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *ptr_file;
ptr_file=fopen("file1.dat","r+");
printf("%c",fgetc(ptr_file));
printf("%c",fgetc(ptr_file));
printf("%c\n",fgetc(ptr_file));
char c;
printf("char:\n");
c=getch();
fputc(c,ptr_file);
return 0;
}
The part where I print the first 3 characters from the file works. After that, I want to put a char into the file. When I compile this, I don't get any errors, but the containing text doesn't change.
Documentation for fopen() standardly shows the following explanation:
When a file is opened with update mode (+ as the second or third
character in the mode argument), both input and output may be
performed on the associated stream. However, output must not be
directly followed by input without an intervening call to fflush(3C)
or to a file positioning function (fseek(3C), fsetpos(3C) or
rewind(3C)), and input must not be directly followed by output without
an intervening call to a file positioning function, unless the
input operation encounters end-of-file.
Just add an fseek() to your code and all works well:
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *ptr_file;
ptr_file=fopen("file1.dat","r+");
printf("%c",fgetc(ptr_file));
printf("%c",fgetc(ptr_file));
printf("%c\n",fgetc(ptr_file));
char c;
printf("char:\n");
c=getch();
fseek( ptr_file, 0, SEEK_CUR ); /* Add this line */
int err = fputc(c,ptr_file);
printf ("err=%d\n", err);
return 0;
}
Here's my file1.dat before and after inputting an 'x':
Before
anahasapples
After
anaxasapples
It seems that by default the fputc() tries to write past the end of the file, so you need to reposition the file pointer (e.g., using fseek) to make the write occur at the point of the current file pointer.
set the pointer first
fseek(ptr_file, ftell (ptr_file), SEEK_SET);
fputc(c,ptr_file);
See this link for explanation http://cplus.about.com/od/learningc/ss/files_8.htm
http://www.rainydayz.org/beej/bgc/fseek.html
Related
I am facing this strange problem, answer to which is clear to me but I am looking for alternative here. Whenever I open a file in "a+" mode, I am able to read using fread(), if I read it first and then write in it using fprintf(). If I instead write into file first and then read it, I get blank value in output.
I do not want to fclose() the FILE pointer fp after every write because I am doing operations like write->read->write->read.......n iterations.
Is there an optimal way to achieve this ?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <linux/input.h>
int main(){
FILE * fp;
fp = fopen("myback.txt", "a+");
char buf[10];
fprintf(fp, "checking");
fread (buf,1,4,fp);
buf[4] = '\0'; //buf has read n bytes
printf("%s \n", buf);
return 0;
}
From this fopen reference:
In update mode ('+'), both input and output may be performed, but output cannot be followed by input without an intervening call to fflush, fseek, fsetpos or rewind, and input cannot be followed by output without an intervening call to fseek, fsetpos or rewind, unless the input operation encountered end of file. In update mode, implementations are permitted to use binary mode even when text mode is specified.
So you can't read or write directly after each other, you must explicitly set or reset the file position between each input and output function.
i wanted to ask you, how to read from file using in C language:
your_program <file.txt
cat file.txt
Line one
Line two
Line three
i have something like that, but it is not working. Thanks a lot
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int vstup;
input = getchar();
while( input != '\n')
printf("End of line!\n");
return 0;
}
You could use freopen() to make stdin refer to the input file instead of the keyboard.
This can be used for input or output redirection.
In your case, do
freopen("file.txt", "r", stdin);
Now stdin is associated with the file file.txt and when you read using functions like scanf(), you are actually reading from file.txt.
freopen() will close the old stream (which is stdin here) "otherwise, the function behaves just like fopen()". It will return NULL if some error occurred. So you better check the value returned by freopen().
Read more about freopen() here and here.
And as others have pointed out, the code as you posted it is probably having an infinite loop as the value of input never changes inside the loop.
compile/link the proposed code into some file, lets call that executable: run
when running the following proposed code, redirect 'stdin' from the input file
./run < file.txt
Here is the proposed code:
// <<-- document why a header is being included
#include <stdio.h> // getchar(), EOF, printf()
//#include <stdlib.h> <<-- don't include header files those contents are not used
int main( void ) // <<-- since the 'main()' parameters are not used,
// use this signature
{
int input; // <<-- 'getchar()' returns an integer and EOF is an integer
while( (input = getchar() ) != EOF ) // <<-- input one char per loop until EOF
{
if( '\n' == input ) // is that char a newline?
{
printf("End of line!\n"); // yes, then print message
}
}
return 0;
} // end function: main <<-- document key items in your code
i'm trying to store the content of a file on a buffer using setvbuf()function in c, this is the code to do so:
#include <stdio.h>
#include <string.h>
int main() {
FILE *fp=fopen("test.txt","r+");
char buff[BUFSIZ];
char buff2[BUFSIZ];
setvbuf(fp,buff2,_IOFBF,BUFSIZ);
fgets(buff,BUFSIZ,fp);
printf("%s\n",buff2);
system("PAUSE");
return 0;
}
and this is the file's content
line 1
line 2
line 3
but when i execute the code, the console shows:
line 1
line 2
line 3 3
where it comes from the additional char at the end of output?.
Whether or in what manner an implementation uses the buffer provided to setvbuf is unspecified. Attempting to derive anything meaningful from its contents while it's associated with a stdio FILE is not something you should be doing.
Any idea why I get 0.000000 with this printf? I checked the file and it was created fine
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
double doub1;
FILE *p;
if((p=fopen("data.txt","wb+"))==NULL)
puts("no");
fprintf(p,"%lf#%lf\n%lf%s",3.9458,314.32133,32.3,"hello");
fscanf(p,"%lf",&doub1);
printf("%lf",doub1);
}
To write to a stream opened with + and read from the same stream you need to flush the output first:
fflush(p);
However this does not reposition the file position indicator. To read characters you already wrote, you need to seek back to them. There is not a separate file position indicator for reading and writing:
fseek(p, 0, SEEK_SET); // go to start of file
The fseek does an implicit flush so you don't need to do fflush if you are doing fseek.
Also, you should check the return value of fscanf before trying to print the output. If the scan failed then you are printing an uninitialized variable.
I wanted to write, read and print to and from the same file. But when the program executes, it can write but it can't read or print the data I have written. When I execute the program, it stops working after writing to the file. I have verified that the file (penny.txt) contains data after the write operation.
I don't know where this is going wrong - how can I read and print the data?
I'm quite new to this, so please take that in mind when answering.
#include<stdio.h>
int main()
{
char ch;
char penny[50],pen[50];
FILE *Object;
Object = fopen("Penny.txt","w+");
fgets(penny, sizeof penny, stdin);
fprintf(Object,penny);
fscanf(Object,"%s",pen);
printf("%s",pen);
return 0;
}
You're at the end of the file when you call fscanf(). Use fseek to return to the beginning:
/* this ignores a whole host of other issues */
fprintf(Object,penny);
/* optional: fflush(Object); */
/* after the call to fprintf you're at the end of the "stream" in this case,
* go back to the beginning:
*/
fseek(Object, 0, SEEK_SET);
/* now we have something to read! */
fscanf(Object,"%s",pen);
printf("%s\n",pen);
You did not notice this problem due to a complete lack of error checking. fopen, fprintf, and fscanf all have error conditions listed, and all use their return value to signal a problem. You ignore these return values at your own peril.
#include<stdio.h>
int main()
{
//char ch;//unused!
char penny[50],pen[50];
FILE *Object;
Object = fopen("Penny.txt","w+");
fgets(penny, sizeof penny, stdin);
fprintf(Object,"%s", penny);//it troubled indicator(%) is included
fflush(Object);//Buffer flush : So that there is no wrote
rewind(Object);//rewind the position of access to the file
fscanf(Object,"%s",pen);
printf("%s",pen);
return 0;
}
You need to Use fseek() to move back the file current position inside the file.
int fseek ( FILE * stream, long int offset, int origin );
Reposition stream position indicator
Sets the position indicator associated with the stream to a new position.
stream
Pointer to a FILE object that identifies the stream.
offset
Binary files: Number of bytes to offset from origin.
Text files: Either zero, or a value returned by ftell.
origin
Position used as reference for the offset. It is specified by one of the following constants defined in exclusively to be used as arguments for this function:
Constant Reference position
SEEK_SET Beginning of file
SEEK_CUR Current position of the file pointer
SEEK_END End of file
*
try this:
#include<stdio.h>
int main()
{
char ch;
char penny[50],pen[50];
FILE *Object;
Object = fopen("Penny.txt","w+");
fgets(penny, sizeof penny, stdin);
fprintf(Object,penny);//now the file is in EOF
fseek(Object,-1*(strlen(penny),SEEK_CUR);//<===move back |penny| in the file
/* optional or:fseek(Object,0,SEEK_SET);<===move to start of file */
fscanf(Object,"%s",pen);
printf("%s",pen);
return 0;
}