Fscanf to get number and replace.


 
Thread Tools Search this Thread
Top Forums Programming Fscanf to get number and replace.
# 1  
Old 07-18-2014
Fscanf to get number and replace.

Hi,
I have a file with contents like "abcd 1234" .What i need is get that integer and replace that with 0. So i used fscanf(fp,"%s %d", str, &num); This is having some problem.
There can be multiple space/tab between string and number. How to replace that number with 0 in same file?
# 2  
Old 07-18-2014
This is having "some problem" -- which some problem? Be specific.

Files don't work that way. You can't delete characters in the middle like a text editor to make it shrink. What pretty much everything does is create a new file, and replace the contents of the old one with it.

Don't use fscanf. It's got "features" most people would consider bugs. Use fgets and sscanf to avoid its buffering problems.

Code:
char buf[4096];
FILE *fpold=fopen("filename", "r");
FILE *fpnew=fopen("newfile", "w+");

while(fgets(buf, 4096, fp) != NULL) // Read all lines from filename one-by-one
{
        int val;
        char *last=(buf+strlen(buf))-1; // Point to last character

        while(isspace(*last)) last--; // Loop backwards across the ending newline
        while(isdigit(*last)) last--; // Loop backwards across digits
        // 'last' now points to the first non-digit before the number.
        last[0]='\0'; // Change it into a NULL.
        last++; // Point to the character after, i.e. the number itself.

        // 'buf' now points to the string and only the string,
        // and 'last' points to the number and only the number.

        sscanf("%d", &val); // convert string into integer

        ////////
        // To alter the contents of the file, alter 'buf' or 'val' here.
        ////////

        fprintf(fpnew, "%s %d\n", buf, val); // Write all contents back into 'fpnew'.
}

fclose(fpold);

// Now, if you really want to, you can re-open fpold as write, read lines one-by-one from fpnew, and write them back into fpold.
rewind(fpnew);
...

# 3  
Old 07-19-2014
I avoid the *scanf*() functions like the plague. If they are passed unvalidated input, results are "undefined". If you're lucky your process will just SEGV and not cause any damage, if you're not you'll get corrupt data in some way.

To validate the input you have to know what it is and what standards to check it against. In other words, you have to parse and interpret the data. Because you pretty much can't safely call one of those functions without doing that.

Once you do that, there's no point in calling one of the *scanf*() functions.
# 4  
Old 07-21-2014
Quote:
Originally Posted by achenle
I avoid the *scanf*() functions like the plague. If they are passed unvalidated input, results are "undefined".
False. They stop scanning at the first result they don't recognize, and return a convenient value to tell you if/where it stopped.

Quote:
If you're lucky your process will just SEGV and not cause any damage, if you're not you'll get corrupt data in some way.
Also untrue. They crash if you give them bad parameters and don't check the return value. So give them good parameters... And check the return value.

fscanf has a buffering problem, as I mentioned above, so sscanf is preferred.
# 5  
Old 07-28-2014
What you say does not make sense.
If you specify a space in the format multiple white space is skipped:



fscanf

"A directive composed of one or more white-space characters is executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character which remains unread."

Bare scanf is not a great idea, use fgets and sscanf:

something like:

Code:
#include <stdio.h>
#include <string.h>

typedef char buffer[128];


char * chomp(char * line)
{
    char **p = &line;
    strsep(p, "\r\n");
    return line;
}

int main( int argc, char **argv )
{
    buffer      in, out;
    int number;

    while ( fgets(in, sizeof in, stdin) ) {
        chomp(in);
        sscanf(in, "%s %d\n", out, &number); 
        printf("%s = %s %d\n", in, out, number);
    }

    return 0;
}


Last edited by bigearsbilly; 07-28-2014 at 06:33 AM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Replace first number of each line in a file with another number

Hi, I have a set of files in a directory that I have to read and replace the first occurrence of a number with another dummy number. This is what I have so far but it does not seem to work. The files have lot of other data in each row and each data element is separated by ,@, for file in... (13 Replies)
Discussion started by: scorpioraghu
13 Replies

2. UNIX for Dummies Questions & Answers

DB2: Replace Number Value

Hi In the below query userreg.status returns a value of 1 (Active) or -1 (Non Active). Ideally, I would like to replace this automatically on the export so instead of getting 1 or -1 I get Active / Non Active. Any help, as usual, would be greatly apprecited. (1 Reply)
Discussion started by: theref
1 Replies

3. UNIX for Dummies Questions & Answers

how fscanf every two data

hi there... i have a question regarding the fscanf function... let's say i have a data: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 how do i read only the first COLUMN, or the second COLUMN or the third COLUMN or etc....?????? thanks (1 Reply)
Discussion started by: theunknown
1 Replies

4. Shell Programming and Scripting

awk - replace number of string length from search and replace for a serialized array

Hello, I really would appreciate some help with a bash script for some string manipulation on an SQL dump: I'd like to be able to rename "sites/WHATEVER/files" to "sites/SOMETHINGELSE/files" within the sql dump. This is quite easy with sed: sed -e... (1 Reply)
Discussion started by: otrotipo
1 Replies

5. Programming

fscanf: read words from file

Hi I have a file like that: 1 2 3 4 5 6 7 8 and I want print on stdout: 1 3 8 in other words i want choose what print out. I was thinking to use fscanf as: fscanf(file_in,"%d %d %d",&a, &b,&c); but in this way i get: 1 2 3 Is there a solution using fscanf to obtain my... (2 Replies)
Discussion started by: Dedalus
2 Replies

6. Programming

C, using fscanf

hey guys, I'm working on a term project for a c/unix class. The basis of the program is that it will calculate the weight/balance of a plane. I'm hoping to have an input file as such: " Pilot weight: Passenger weight: baggage wieght: etc " and the idea is that I'm trying to use... (2 Replies)
Discussion started by: jlangholzj
2 Replies

7. Programming

read a file wich fscanf() in a function

I use fopen, fscanf, fclose to read a file. It can work well. since many files should be read, a function is created with the same code. But in the function, fscanf can not work well. for example, the first line of the the file is: > filename but the fscanf will give: 207/23/eee/34 it appears... (2 Replies)
Discussion started by: cdbug
2 Replies

8. Programming

fscanf

Hi, Can any one tell me what "%hx" as control parameter mean in fscanf. Thanks, abey (4 Replies)
Discussion started by: abey
4 Replies

9. Programming

fscanf()

I keep trying to use fscanf() and for some reason I can't get the syntax down and always get seg faults. I'm on a SunOS 5.5.1, and my current code looks like this: int n1, n2, n3, n4, n5, n6; /* open config file */ if (fileptr = fopen(filename,"r") == NULL) { printf("couldn't open... (3 Replies)
Discussion started by: j_t_kim
3 Replies

10. Programming

fscanf()

thanks to everyone for your earlier replies, but i have yet another problem with file i/o. i'm trying to read multiple lines with the same file, and have been using the following code to take in the first two lines from a file... fscanf(fileptr, "%d %d %d %d %d %d\n", &n1, &n2, &n3, &n4, &n5,... (1 Reply)
Discussion started by: j_t_kim
1 Replies
Login or Register to Ask a Question