473,735 Members | 2,093 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problems using fgets() and sscanf() while modifying file contents

hi all, this is reddy, a beginner to c lang,,here i have some problems
in reading and modifying the contents of a file,, hope you can help to
solve this problem. Here i attach the file to be modified and the
program code.
In the attached file below i just want to change the value of
data(only float value) after the line 1 P V T 1 15 till 2 G TT,
from positive to negative and vice versa, and wire the date in other
file. can someone help me to solve this.
thanks.
*** MEAS(T,L) DATA ***
/07/07

T
8
PINION
3
2
2
119.6329
-113.2538
74.8409
2.0000
1 P V T 1 15
20 -6.2
21 -4.0
22 0.7
1 P V L 1 5
23 3.9
24 -5.1
25 5.2
26 -5.7
1 P V T 3 15
27 5.9
28 -5.2
2 G TT
1 1.2488
3 1.2598
END
program code:
do {

if (c=fgets(file1, sizeof file1, in1) !='\n'
&& sscanf(file1,"% d %f",&num,&value ) == 2)
{
value= (value- (2*value));
printf("%d %1.1f\n", num, value);
fprintf(append3 ,"%d %1.1f\n", num, value);
}
else
{
for(j=0;;j++){
printf("%c",fil e1[j]);
fprintf(file2," %c",file1[j]);
if(file1[j]=='\n')break;}

}

} while (!feof(in1));

return EXIT_SUCCESS;

Jul 15 '07 #1
24 2960
allpervas...@gm ail.com wrote:

[ ... ]
In the attached file below i just want to change the value of
data(only float value) after the line 1 P V T 1 15 till 2 G TT,
from positive to negative and vice versa, and wire the date in other
file. can someone help me to solve this.
thanks.

*** MEAS(T,L) DATA ***
/07/07

T
8
PINION
3
2
2
119.6329
-113.2538
74.8409
2.0000
1 P V T 1 15
20 -6.2
21 -4.0
22 0.7
1 P V L 1 5
23 3.9
24 -5.1
25 5.2
26 -5.7
1 P V T 3 15
27 5.9
28 -5.2
2 G TT
1 1.2488
3 1.2598
END
program code:
This is not a program. This is just a code snippet.
do {

if (c=fgets(file1, sizeof file1, in1) !='\n'
fgets returns a null pointer, if end-of-file or an error occurs,
otherwise it returns file1. Here you're checking it's return value
against the newline character. The result of this test, either 1 or 0
for true or false gets assigned to c. ITYM something else.
&& sscanf(file1,"% d %f",&num,&value ) == 2)
{
value= (value- (2*value));
printf("%d %1.1f\n", num, value);
fprintf(append3 ,"%d %1.1f\n", num, value);
}
else
{
for(j=0;;j++){
printf("%c",fil e1[j]);
fprintf(file2," %c",file1[j]);
if(file1[j]=='\n')break;}

}

} while (!feof(in1));
You need to check the fgets call for a null pointer return. That could
be because of both end-of-file, (true if feof() returns true), or
other error, (true if ferror() returns true). So here you should check
for both outcomes.

<snip>

Jul 15 '07 #2
ya i checked the fgets using null pointer also,, but the there is no
change,,
actually iam able to change the data(float value) from +ve to -ve and
vice-versa but the problem is that even the data before the line
"1 P V T 1 15" and after the line "2 G TT" gets changed as shown
below, so i need a better approach to solve that bug. thanks

original data:

*** MEAS(T,L) DATA ***
/07/07
..
..
119.6329
-113.2538
74.8409
2.0000
1 P V T 1 15
20 -6.2
21 -4.0
22 0.7
..
..
2 G TT
1 1.2488
3 1.2598
END


modified data:

*** MEAS(T,L) DATA ***
/07/07
..
..
119 -0.6
-113 -0.3
74 -0.8
2 0.0
1 P V T 1 15
20 6.2
21 4.0
22 -0.7
..
..
2 G TT
1 -1.2
3 -1.3
END
END

Jul 15 '07 #3
allpervas...@gm ail.com wrote:
ya i checked the fgets using null pointer also,, but the there is no
change,,
actually iam able to change the data(float value) from +ve to -ve and
vice-versa but the problem is that even the data before the line
"1 P V T 1 15" and after the line "2 G TT" gets changed as shown
below, so i need a better approach to solve that bug. thanks
<snip>

I'll suggest a general algorithm:

Read each line of data file
If line matches desired pattern, (in this case, "1 P VT 1 15")
If next line _does not_ match closing pattern, (i.e., "2 G
TT")
Convert the line into appropriate numerical values
Change the value you want to change
Write out the modified values
Repeat from step three above

Basically you need to enter your main modification loop only after you
detect the opening pattern and exit it after you detect the closing
pattern. Before the opening pattern and after the closing pattern you
should write out the file unmodified. I suggest encapsulating the
modification code into a separate function. The patterns can be
detected with the standard string functions in string.h.

Jul 15 '07 #4
al**********@gm ail.com writes:
hi all, this is reddy, a beginner to c lang,,here i have some problems
in reading and modifying the contents of a file,, hope you can help to
solve this problem. Here i attach the file to be modified and the
program code.
In the attached file below i just want to change the value of
data(only float value) after the line 1 P V T 1 15 till 2 G TT,
from positive to negative and vice versa, and wire the date in other
file. can someone help me to solve this.
thanks.
I know this is comp.lang.c but there are cases where it is worth
suggesting another route: <OT>Perl and AWK can this kind of thing with
ease. If you are fluent in C, so can C, but the time spent learning
one of these other tools will pay off big time over a lifetime.</OT>
program code:
A whole program is more useful.
do {
if (c=fgets(file1, sizeof file1, in1) !='\n'
&& sscanf(file1,"% d %f",&num,&value ) == 2)
{
value= (value- (2*value));
printf("%d %1.1f\n", num, value);
fprintf(append3 ,"%d %1.1f\n", num, value);
}
else
{
for(j=0;;j++){
printf("%c",fil e1[j]);
fprintf(file2," %c",file1[j]);
if(file1[j]=='\n')break;}
}

} while (!feof(in1));
Using "do" is almost always wrong -- it tends to twist program logic.
Using feof to end an input loop is also almost always wrong (see the
FAQ about that).

You want to do something for every line read so say that:

while (fgets(file1, sizeof file1, in1) != NULL) {

(You will have problems if there are lines longer than will fit in
your buffer, but let's leave that for now.)

You will need to know if you are in the region of interest, so you will
have a variable to record that fact.

if (in_region && sscanf(file1, "%d %f", &num, &value) == 2) {
printf("%d %1.1f\n", num, -value);
fprintf(append3 ,"%d %1.1f\n", num, -value);
continue;
}

I put a "continue" in there because I know we have done all we need to
do with such a line[1].

You need to note coming into and leaving the region of interest:

if (file1[2] == 'P')
in_region = 1;
else if (file1[2] == 'G')
in_region = 0;

And, lastly, you need to print any data not yet dealt with. You don't
need a loop to that, fputs is there to help:

fputs(file1, stdout);
fputs(file1, file2);
}

I am not sure what "file2" and "append3" are, but I assumed those
parts are correct.

[1] I am not a fan of continue, but it is handy in some explanations.

--
Ben.
Jul 15 '07 #5

thanks a lot for ur suggestions,, now i could get the desired output..
but i still have a small question,,how can i print a new line using
fprintf

using- fprintf(append3 ,"%d %1.1f\n", num, -value); iam unable to
get the output in a new line, instead i get
it in a single line. could u please help me how to do that. I also
tried to use fprintf(append3 , "\n"); but still i couldnt get it.

thanks

Jul 15 '07 #6
On Sun, 15 Jul 2007 07:54:09 -0000, al**********@gm ail.com wrote:
>hi all, this is reddy, a beginner to c lang,,here i have some problems
in reading and modifying the contents of a file,, hope you can help to
solve this problem. Here i attach the file to be modified and the
program code.
You obviously know that sentences end with a period and how to find
the shift key on your keyboard. Is there,,some,,re ason,,you
deliberately chose to make your text difficult to read?
>In the attached file below i just want to change the value of
data(only float value) after the line 1 P V T 1 15 till 2 G TT,
from positive to negative and vice versa, and wire the date in other
file. can someone help me to solve this.
thanks.
What problem are you having? You don't show the code that checks for
the two lines of interest. You don't tell us what values you see in
your output file. Your code violates the rules of the language. If
you want help, you need to give us enough information so we don't have
to guess.

snip input data

I have reformatted your code to make it readable. Please indent
consistently. Also, for code you post, use spaces, not tabs.
>program code:
do {

if (c=fgets(file1, sizeof file1, in1) !='\n'
&& sscanf(file1,"% d %f",&num,&value ) == 2)
You are missing parentheses in this expression. As a result, it is
not doing what you intend. The operators with the highest precedence
in this expression are != and ==. That causes your expression to be
evaluated as
c = (fgets(...) != '\n') && (sscanf(...) == 2)
The next operator with the highest precedence is && which results in
c = ((fgets(...) != '\n') && (sscanf(...) == 2))
Note that this assigns to c the result of a boolean expression, which
will always be 0 or 1.

Furthermore fgets returns a pointer. '\n' is an int. You cannot
compare a pointer to an int without an explicit conversion, which you
would not want to do anyway. Your compiler should have issued a
diagnostic here. Did it? Why did you ignore it? Since you don't use
c in the posted code, I cannot tell if you wanted to compare the
return from fgets to NULL or if you really wanted to use fgetc to
extract a single character. Since you do use file1 in the expression
after the &&, I assume the former and your code should look something
like
if ((fgets(...) != NULL) && (sscanf(...) == 2))
Technically, the two sets of internal parentheses surrounding the two
operands of && are superfluous but until you become more familiar with
precedence they are cheap insurance.
{
value= (value- (2*value));
This is "equivalent " to
value = -value;
which matches your stated intent and has the additional virtue of
avoiding "rounding errors".
printf("%d %1.1f\n", num, value);
fprintf(append3 ,"%d %1.1f\n", num, value);
}
else
{
for(j=0;;j++){
printf("%c",fil e1[j]);
fprintf(file2," %c",file1[j]);
putc and fputc would be simpler here.
> if(file1[j]=='\n')break;}
You have a logic error here. fgets stores a \n in the input buffer
only if the input "line" is shorter than the buffer. You also need to
terminate the for loop if j exceeds the size of the buffer. The
easiest way to do that is to populate the second clause of the for
statement with something like j < sizeof file1 - 1. (Think about why
you never want to process file1[sizeof file1 - 1] in this loop.)
>
}

} while (!feof(in1));
Your description said you wanted to stop this conversion at 2 G TT.
The loop you show us has no code to check for this line.

There is another logic error here. fgets can return NULL for reasons
other than end of file. If you experience an I/O error, this code
will continue the loop and try to read more data from a broken stream.
>
return EXIT_SUCCESS;

Remove del for email
Jul 15 '07 #7
al**********@gm ail.com writes:
thanks a lot for ur suggestions,, now i could get the desired output..
but i still have a small question,,how can i print a new line using
fprintf

using- fprintf(append3 ,"%d %1.1f\n", num, -value); iam unable to
get the output in a new line, instead i get
it in a single line. could u please help me how to do that. I also
tried to use fprintf(append3 , "\n"); but still i couldnt get it.
Sounds odd. Please post a short program (maybe just main with a file
open and an fprintf call?) that exhibits this problem. Here,

#include <stdio.h>

int main(void)
{
FILE *f = fopen("out", "w");
if (f) {
fprintf(f, "two\nlines\n") ;
fclose(f);
}
return 0;
}

does exactly what I'd expect it to.

--
Ben.
Jul 15 '07 #8
al**********@gm ail.com wrote:
>
thanks a lot for ur suggestions,, now i could get the desired output..
but i still have a small question,,how can i print a new line using
fprintf
Please quote a representative sample of the previous message to give
context to your reply. Google Groups does that automatically for you.
When you do, trim the quotes to leave the necessary part and interleave
your replies.

See the vast majority of other posts in the newsgroup.


Brian

Jul 15 '07 #9
On Sun, 15 Jul 2007 13:58:57 -0000, al**********@gm ail.com wrote:
>
thanks a lot for ur suggestions,, now i could get the desired output..
but i still have a small question,,how can i print a new line using
fprintf

using- fprintf(append3 ,"%d %1.1f\n", num, -value); iam unable to
get the output in a new line, instead i get
it in a single line. could u please help me how to do that. I also
tried to use fprintf(append3 , "\n"); but still i couldnt get it.
What do you want on a new line?

Is the text from this fprintf showing up on the same line as a
previous fprintf? If so, that fprintf probably doesn't end with a \n.
You could add a \n at the beginning of this fprintf but fixing the
previous one is usually a better idea.

Do you want the two values from this frpintf on different
lines? If so, then insert a \n between the two format conversions.

If you want help with a problem, please provide enough detail:
what is the current result.
what is the desired result.
if it is not immediately very obvious, what is the difference
between the two.
cut and paste the code which is causing the problem,
preferably as a ready to compile and run complete program.

And unless you want to be Ignored,,as,,de lIberately,,obn oxIous, you
wIll make some effort to use readable EnglIsh
Remove del for email
Jul 15 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3045
by: Andrej Hocevar | last post by:
Hello, below I've attached a test program reading data from a file and storing that information in a linked list. First problem is that current->p_name will print only the last item in the file for each item. Where is the problem? Is it in the sscanf? Whay can't I abandon tmp_name and just use p_name instead in that sscanf? Second, the order of the output (with a file of 3 lines) is 1, 2, 0, why? And why is the item 0 empty? I'm new to...
6
5606
by: Eirik | last post by:
Hey, all groovy C programmers, I've read in the FAQ(question 12.18) about how applications skip calls to (f)gets() after scanf() has been used. How can I avoid this? I know that I can by putting the fgets() before the scanf(). However, this one is not always suitable. Do you know of any other ways of avoiding this problem? -- - Fordi det rotar til måten folk vanlegvis les tekst på.
4
2159
by: interpim | last post by:
ok the function is supposed to accept only non-negative integers... but it still accepts letters input through the function. Such as '23e' still passes through. I tried to use isalpha in the or statement to cause an error, but it causes an error for everything input. How do I make an error occur when anything other than numbers are put in? #include <stdio.h> #define MAXLINE 20 int main(void) { char line; int error,n; do{...
6
3500
by: hpy_awad | last post by:
I am writing stings ((*cust).name),((*cust).address)to a file using fgets but rabish is being wrote to that file ? Look to my source please and help me finding the reason why this rabish is being written. /* Book name : File name : E:\programs\cpp\iti01\ch10\ex09_5p1.cpp Program discription: Adding name,Address to customer_record SETUP PROGRAM
3
1347
by: Tcc | last post by:
Hi all, Assume there are some data in a file "a.txt": abc def 11<---------------------data in a.txt is it possible for me to use "fgets" function to get the string "abc", "def" and "11" individulely? and How?
3
2298
by: kimimaro | last post by:
hi below is my save function that is used to placed data from the C program to a text file for future usage. void save() { FILE *save; int i = 0; save=fopen("employeerecord.txt", "a+");
1
4286
by: anonymous | last post by:
I'm having a LOT of trouble figuring out how to read input from a file into my program. This file contains lines with an arbitrary number of words in them. For example: This is one line in my file However the next line has far more words in it This has the least I'm trying to read each whole line, then read each word from the line, as follows: while (fgets(line, MAX_LINE_LEN, inputfile) != NULL)
2
3088
by: jou00jou | last post by:
Hi, I have trouble using sscanf and fgets to check for overflow. I will post the assignment specification so I could help whoever would kindly like to offer his/her help. ____________________________________________________________________________________ 1) The program should expect 2 decimal integers per line. Let's call these n1 and n2. 2) For each such input line it should output the value of n1 + 2 * n2 (followed by a newline...
2
3984
by: jorba101 | last post by:
I'm having following trouble: I'm reading contents of a string retrieved from a CSV-like file with sscanf, in following way: sscanf( originalString, "%d,%s,%s", &myInteger, myString1, myString2 ); originalString contents are something like: char originalString="1,my text here 1,my text here 2";
0
8959
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8784
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9326
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9248
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8199
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6049
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4558
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4821
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2738
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.