c: fopen and fprint - c

as I understood, In the next code:
int main () {
FILE * f1;
f1 = fopen("f1.txt","a");
for (i =0 ; i<10;i++) fprintf(f1,"%d ",i);
fclose(f1);
f1 = fopen("f1.txt","a");
for (i =0 ; i<10;i++) fprintf(f1,"%d ",i);
fclose(f1);}
I will get in File f1, the next serial: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9. I didn't understand why. When I close the file, and open it again, it doesn't remember the end file. I expected that the second loop will override the text that was there before, and I will get just 0 1 2 3 4 5 6 7 8 9. So - what happened?

It's because you open the file in mode "a", which stands for append. The new text gets added to the end of the file.
If you want to write over what's already there, replace the second fopen with:
f1 = fopen("f1.txt", "w");
"w" stands for write, and will replace what's already there with your new text.

"a" means append; perhaps you want "w" (write) instead?

You opened the file in append-mode when you passed "a" as the second argument to fopen, so it appended the data.

Related

C Writing into file stop working after use it as function?

I wrote a function that sets every number of a line in a .txt file to zero and clears the other file.
I originally wrote this logic in main and it worked perfectly fine. But now I need to make a menu for my program, so I need to put this logic into a function.
That's where the things go wrong. Once I move the logic into a function, it doesn't set the numbers to zero, it just clears the file, and I didn't changed anything.
Expected result:
Workers.txt : Adam Washington Monday Friday --(use function)--> {clear}
days.txt: 1 0 0 0 1 0 0 --(use function)--> 0 0 0 0 0 0 0
Actual result:
It's clear in both files.
void ResetOwnData(){
printf("--------------------------------------------------------------------------\n");
FILE* freset = fopen ("workers.txt", "w");
close(freset);
FILE* freset2 = fopen ("days.txt", "w");
for(int i = 0; i < 7; i++){
fprintf(freset2,"%d ",i+1);
}
fprintf(freset2,"\n");
for(int i = 0; i < 7; i++){
fprintf(freset2,"%d ",0);
}
close(freset2);
printf("Everything get reset!\n");
printf("--------------------------------------------------------------------------\n");
}
There are two main things that appear to be incorrect.
You are using close rather than fclose. fclose is used with file streams (like you are using)
Your function is overwriting the one line that you want (e.g., 0 0 0 0 0 0 0) with two lines because you have two for loops
Here is a CodingGround link to the corrections that I believe you are seeking.
You should add some error checking to ensure that you truly have opened the file and that you release any allocated memory

Adding Line break After Every Line

I have written the following piece of code:
#include<stdio.h>
void add_linebreak()
{
FILE *fp ;
char c, NEWL=10 ;
fp=fopen("text1.txt","a+") ;
if(fp==NULL)
{
printf("\nFile Not Found") ;
}
fseek(fp,0,SEEK_CURR) ;
while(!feof(fp))
{
//if(!feof(fp))
//{
c=fgetc(fp);
if(c==NEWL)
{
fprintf(fp,"%c",NEWL) ;
}
//}
}
fclose(fp) ;
}
int main()
{
add_linebreak() ;
printf("\nEditing Complete") ;
return 0 ;
}
The program took following data as input from a file named text1.txt :
1 this
2 is
3 a
4 text
5 file
6 to
7 test a
8 program
9 written
10 in c
Actual Output :
1 this
2 is
3 a
4 text
5 file
6 to
7 test a
8 program
9 written
10 in c
11
Expected Output:
1 this
2
3 is
4
5 a
6
7 text
8
9 file
10
11 to
12
13 test a
14
15 program
16
17 written
18
19 in c
20
I scratched my head on this for hours but wasn't able to get the expected output, please help me.
you gotta make a copyy of the file
Also fgetc returns int not char
void add_linebreak()
{
FILE *fin, *fout ;
char NEWL='\n' ;
fin=fopen("text1.txt","rb") ;
if(fp==NULL)
{
printf("\nFile Not Found") ;
}
fout = fopen("copy.txt","w");
while(1)
{
int c=fgetc(fin);
if(c==EOF)
break;
fprintf(fout, "%c", c);
if(c==NEWL)
{
fprintf(fout,"%c",NEWL) ;
}
}
fclose(fout) ;
fclose(fin);
}
renaming the file back to the original and adding some more error handling is left as a test :-)
You may not perform the modifications in-place. Not with stuff like text.
You have to instead read from one file, write to a temporary then perhaps rename the copy to overwrite the original update.
The other answer says almost everything besides the rename.
Oh, another thing: I have found often that newlines tended to get stripped in my old test programs; that may be another thing. But the modifying-in-place is the most likely culprit.

Gnuplot and C "x range is invalid"

I'm trying to generate a data file and to plot it with Gnuplot. The problem is when I keep my Nstep lower than 348 I get the error
line 0: warning: Skipping data file with no valid points
plot 'plot.txt' using 1:2 with lines
^
line 0: x range is invalid
But I keep the Nstep higher than 348 everything works fine. I do not understand why. Here is my C code:
int main(void){
int Nstep = 348;
//omitted part...
FILE *pipe = fopen("plot.txt", "w+");
while (n<Nstep) {
pos[n+1] = pos[n] + v[n]*h;
v[n+1] = v[n] + h * Fx(pos[n]);
fprintf(pipe, "%d %05.3lf\n", n, v[n]);
n++;
}
close(pipe);
system("gnuplot -p -e \"plot 'plot.txt' using 1:2 with lines\"");
return 0;
}
plot.txt example (Nstep = 10)
1 100.000
2 99.000
3 97.000
4 94.010
5 90.050
6 85.150
7 79.349
8 72.697
9 65.252
10 57.079
I am unable to replicate your error as you didn't include the full source (function Fx and definitions of pos and v). You are calling the wrong close. You should call fclose() (this will flush the file handle too).
fclose(pipe)
And not
close(pipe)
You could explicitly flush the data by calling fflush().

fscanf not able to read the values

I am trying to read a text file using fscanf.I am working in eclipse in OpenCV on ubuntu.
Here are some sample values in the text file
0 5 7 0.547619047619048 1 0.0274509803921569 1
0 6 8 0.541666666666667 1 0.0313725490196078 1
0 8 10 0.533333333333333 1 0.0392156862745098 1
But all fscanf reads is zeros in the array.Here is the part of the code that reads the values
long double testd[1000][6]
FILE* fid1=fopen("file","r");
while((fscanf(fid1,"%Lf",&b))==1)
{
printf("%Lf\n",b);
testsamplecount=testsamplecount+1;
}
for (i=0;i<testsamplecount/6;i++)
{
fscanf(fid1,"%Lf %Lf %Lf %Lf %Lf %Lf",
&testd[i][0],&testd[i][1],
&testd[i][2],&testd[i][3],
&testd[i][4],&testd[i][5]);
}
testd[i][0], etc, is an rvalue. What you need is &testd[i][0].
The first loop consumes the file. Try rewind(fid1); between the loops.
Edit: alternatively, as an option maybe a little more laborious but twice as performant, do a single loop, reading until there is no more data.
I think you don't move the file pointer to the start point of the file.
Use the library fseek(fp, 0, 0) or
Try close the file and then open again.

jumping to the a wanted line and overriding the first letter inside it in c

hello i am trying to write to a FILE in a wanted line number using c programming language
and for some unknown reasons it doesnt get written
this is my checking code:
int main()
{
int x;
int counter = 0;
char buffer[MAX];
FILE* fp = fopen("sale_day.txt","w");
fprintf(fp,"5 orange 11\n");
fprintf(fp,"4 pelephone 222\n");
fprintf(fp,"3 mirs 4000\n");
fprintf(fp,"2 cellcom 302\n");
fprintf(fp,"1 tmobile 500\n");
fclose(fp);
fp = fopen("sale_day.txt","r+");
while (counter < 2)
{// jumping two rows
fgets(buffer,MAX,fp);// i tried using fscanf which didnt help aswell
counter++;
}
fflush(fp); // i tried with and without still doesnt work
fputs("$",fp);
fflush(fp); // i tried with and without still doesnt work
fclose(fp);
}
i expect to get :
5 orange 11
4 pelephone 222
$ mirs 4000
2 cellcom 302
1 tmobile 500
for some reason it stays as the following in "sale_day.txt" file
5 orange 11
4 pelephone 222
3 mirs 4000
2 cellcom 302
1 tmobile 500
even tho when i debug it it shows a "$" instead of the 3 digit
thanks in advance for your help !
The code works just fine, also without the fflush-lines. After running the program, line 3 is changed as follows:
Before:
3 mirs 4000
After:
$ mirs 4000
I ran your code like it is, only with this on top:
#include <stdio.h>
#define MAX 255
What are you expecting? When I run your code, I get:
5 orange 11
4 pelephone 222
$ mirs 4000
2 cellcom 302
1 tmobile 500
This is exactly right given what you've coded: read two lines (leaving you positioned at the third line), and write a $ char.
Note that file write operations overwrite existing file data, or append new data to the end of a file. They don't insert data (which may have been the operation you're expecting).

Resources