473,763 Members | 4,808 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 2966
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
3047
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
5608
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
2160
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
3501
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
1348
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
2299
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
4288
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
3985
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
9563
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
10144
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9997
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
9937
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
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8821
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3522
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.