Thread: read part from file

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    18

    read part from file

    i have file like this :
    width 95 - 78,90,91

    i need to read the numbers 95 and 91
    how can i scan this nubmer into two integer ?
    my code so far :

    Code:
    while ((ch = fgetc(f1)) != EOF) {     
           while (((ch = fgetc(f1)) != 'h') && (ch != EOF)) {}
                fscanf_s(f1, "%d\n", &j);
        
            }
    now i got only the width

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Use fgets() to read a whole line into memory.

    Then perhaps
    Code:
    char buff[BUFSIZ];
    fgets(buff,BUFSIZ,f1);
    sscanf(buff, "width %d - %*d,%*d,%d", &n1, &n2);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2020
    Posts
    18
    Quote Originally Posted by Salem View Post
    Use fgets() to read a whole line into memory.

    Then perhaps
    Code:
    char buff[BUFSIZ];
    fgets(buff,BUFSIZ,f1);
    sscanf(buff, "width %d - %*d,%*d,%d", &n1, &n2);
    oh i forgot to say my file looks like :
    width 95 - 78,90,91
    78,90,91
    788,90,901
    78,901,91
    width 95 - 78,90,901

    and i need only the nubmers where the line start with width

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    if ( sscanf(buff, "width %d - %*d,%*d,%d", &n1, &n2) == 2 )
    This will ignore lines not matching the expected format.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File processing: How to read a part of a text file?
    By HardOverdrive in forum C Programming
    Replies: 4
    Last Post: 12-05-2011, 12:33 PM
  2. read part of text in file
    By eldy in forum C++ Programming
    Replies: 1
    Last Post: 11-23-2011, 12:54 PM
  3. read part of png file
    By fleurdelys in forum Game Programming
    Replies: 8
    Last Post: 10-23-2011, 04:19 AM
  4. Read part of file
    By Martin Kovac in forum C Programming
    Replies: 1
    Last Post: 04-13-2009, 01:51 PM
  5. Deleting part of a file
    By Invincible in forum C++ Programming
    Replies: 5
    Last Post: 05-23-2002, 02:08 AM

Tags for this Thread