Thread: reading integers using fgets

  1. #1
    Registered User
    Join Date
    Jul 2008
    Location
    Barcelona
    Posts
    41

    reading integers using fgets

    How can i read some integer from file using fgets or at least cast them?
    I am reading from a file like this
    Code:
    char master[BUFSIZ], slave[BUFSIZ], lin[BUFSIZ], col[BUFSIZ];
    int nlin, ncol;
    
    skipped code...
    
    		fgets(master,sizeof(master),fp);
    		// remove newline
    		if ((p = strchr(master, '\n')) != NULL) *p = '\0';
    
    		fgets(slave,sizeof(slave),fp);
    		// remove newline
    		if ((p = strchr(slave, '\n')) != NULL) *p = '\0';
    		
    		
    		fgets(lin,sizeof(lin),fp);
    		// remove newline
    		if ((p = strchr(lin, '\n')) != NULL) *p = '\0';
    		nlin = (int) lin;
    
    		fgets(col,sizeof(col),fp);
    		// remove newline
    		if ((p = strchr(col, '\n')) != NULL) *p = '\0';
    		ncol = (int) col;
    The first two fgets works fine and then I need integers in nlin and ncol to pass on, but I dont know how to read them or cast them properly properly, now I get big numbers like 1234000 which is not right. Anybody?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Use strtol to change a bunch of characters into a (long) int.

  3. #3
    Registered User
    Join Date
    Jul 2008
    Location
    Barcelona
    Posts
    41
    Perfect, thanks

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It looks like you could do with putting these two lines into a function:
    Code:
    		fgets(col,sizeof(col),fp);
    		// remove newline
    		if ((p = strchr(col, '\n')) != NULL) *p = '\0';
    // and possibly also the conversion to integer - but that would probably be better in a separate function.
    Any time you find yourself repeating almost identical code more than twice for more than two or three lines, you shoudl ALWAYS ask yourself "is it better to split this out to a separate function".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem using sscanf fgets and overflow checking
    By jou00jou in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 06:42 AM
  2. Replies: 2
    Last Post: 01-28-2008, 03:07 AM
  3. Error if reading char or float
    By sh4k3 in forum C Programming
    Replies: 3
    Last Post: 06-07-2007, 03:06 PM
  4. Fgets + sscanf
    By MethodMan in forum C Programming
    Replies: 3
    Last Post: 03-15-2004, 08:53 PM
  5. Array, reading in response etc...
    By mattz in forum C Programming
    Replies: 4
    Last Post: 12-05-2001, 11:41 AM