Thread: File I/O format

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    3

    File I/O format

    Hello,

    I'm a novice programmer working on file I/O. Apologies in advance if the question is simple, or if similar questions are already posted. I searched the most recent posts tagged with "file I/O" but didn't see similar entries...

    That aside, I'm trying to read from a text file for a particular character or set of characters, then read the integer directly following it,

    for example,

    .i 2

    I'd want to look for the '.i' (and there should be a space after that) then an integer. I'm trying to read the integer now, and I'd like to save it as a variable for later use

    Code:
    for(i=1;i<3;++i) {
     while((imat[i]=getc(inp))!=EOF) //input matrix of type char; inp is input file pointer
     if(imat[1]=='.'&& imat[2]=='i') // look for '.i'
     fscanf(inp, "%s", letternum); //letternum is array of length 1; char letternum[1]
     num = atoi(letternum); //convert string letternum to integer
    fprintf(outp, "%d\n",num); //print integer in file to see what is being read
     }
    all I get are two zeros in output file for an input file of .i 2 where I'd hope to get 2.

    Anyone able to give me an idea of how I can read the 2 following a .i?

    Much appreciation

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I think you should hand this in and tell me what grade i got

    Anyway, your for loop will give you problems because when i==1, unless you have zeroed out imat (have you allocated it memory at all?) you won't know what imat[2] will be (shouldn't these be 0 and 1, not 1 and 2? It's the same problem anyway) but whatever it is, it won't be something read from the file. Actually your for loop is quite messed up, I think; "i" will not iterate as part of the inner while loop, so it will always be 1 while you are reading from the file, so you will always overwrite the previous character and be unable to find ".i" If you want to rewrite it a bit and ask again I might be able to help you further.

    Also make your fscanf line more specific and just grab the int. I used sscanf because of my method, but it works the same:
    Code:
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    char *buffer=NULL;
    
    int nextline (FILE *stream) {
    	int chr, i=0;
    	if ((buffer=malloc(2))==NULL) return -1;
    	while ((chr=fgetc(stream))!=EOF) {
    		if (chr=='\n') {
    			buffer[i]='\0';
    			return i+1;
    		}
    		buffer[i]=chr;
    		i++;
    		if ((buffer=realloc(buffer,i+2))==NULL) return -2;		
    	}
            buffer[i]='\0';
    	return 0;
    }	
    
    
    int main() {
    	char *ptr, lookfor[2]=".i";
    	int llen, found;
    	FILE *fstRO=fopen("/root/test/text.txt","ro");
    	if (fstRO==NULL) {
    		puts("Couldn't open file...");
    		return -1;
    	}
    	
    	while ((llen=nextline(fstRO))!=0) {
    		if (llen<0) {
    			printf("in nextline(): Memory Allocation Failed! (&#37;d)\n",llen);
    			return -2;
    		}	
    		while (((ptr=strchr(buffer,lookfor[0]))!=NULL) && ptr[1]==lookfor[1]) {
    			if ((sscanf(ptr,".i%d",&found))==1) printf("Found a %d...\n",found);		
    			ptr[0]=' ';	
    		}
    		free(buffer);
    	}
    	puts("Done.");
            fclose(fstRO);
    	return 0;
    }
    The input test file I used looked like this:

    Code:
    Jamie lynn:20
    Eric D. Mcdaniel:40
    
    	.i10001    12
    
    
    Joe:20
    .i 2  then .i 624
    more .i 7
    1234567890
    etc
    .i44  20081117_ABC1E_1_Prod
    20081118_DEF5G_3_Prod
    20081117_ABC1E_12_Prod
    and my output was:

    Found a 10001...
    Found a 2...
    Found a 624...
    Found a 7...
    Found a 44...
    Done.
    Last edited by MK27; 11-29-2008 at 11:45 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    The first time through your WHILE loop when i==1, you will hit EOF, with variable "i" still matching 1, because imat[2] has never gotten set. In other words, the fscanf() will never get executed in loop #1.

    After you hit EOF and the WHILE loop ends, you convert letternum (which is not initialized) to an int and print it out.

    The second time through the loop, when i==2, the first time in your WHILE loop condition, the getc() will hit EOF immediately, (it is still sitting at EOF from loop #1), so again, the fscanf() will not be run and you will convert letternum to an int.

    To prove this to yourself, set letternum equal to some value (like "42" via strcpy( letternum,"42") ; ) before your loop and see what prints out.
    Mainframe assembler programmer by trade. C coder when I can.

  4. #4
    Registered User
    Join Date
    Nov 2008
    Posts
    3

    Thanks for respsonses

    Thank you for replying; I'm about to implement your code now and check it out. I've never used malloc() before (remember, I'm just a novice) so I'm looking up what it does, but then I'll try out the code you posted. Thanks!

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    If you haven't covered malloc() yet, you will soon, so don't worry about it. Since I know the length of the lines in the file, I could have done this to make it simpler (a static buffer):

    Code:
    char buffer[64];      // no longer needs to be malloc'd
    
    int nextline (FILE *stream) {
    	int chr, i=0;
    	while ((chr=fgetc(stream))!=EOF) {
    		if (chr=='\n') {
    			buffer[i]='\0';
    			return i+1;
    		}
    		buffer[i]=chr;
    		i++;
    	}
    	buffer[i]='\0';
    	return 0;
    }
    And then remove "free(buffer)" from main().

    I also forgot to include the line in red before (methinks I'll go back and edit the post) which will cover the case where the last line of the file doesn't have a newline.

    Good luck and happy coding.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Registered User
    Join Date
    Nov 2008
    Posts
    3

    Thanks again!

    Hi,

    Just tried the code both ways. It works perfectly! That's exactly what I needed. I'm reading up on dynamic memory allocation now so I can use this technique again for similar cases. Thanks for your help; I'd give you an A+!

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by MK27
    Since I know the length of the lines in the file, I could have done this to make it simpler (a static buffer):
    To avoid buffer overflow:
    Code:
    #define BUFFER_MAX_SIZE 64
    char buffer[BUFFER_MAX_SIZE]; /* no longer needs to be malloc'd */
    
    /* ... */
    
    while (i < BUFFER_MAX_SIZE && (chr=fgetc(stream))!=EOF) {
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Question about file I/O from a newbie
    By henrik in forum C Programming
    Replies: 4
    Last Post: 11-13-2007, 12:48 AM
  3. File I/O Question
    By Achy in forum C Programming
    Replies: 2
    Last Post: 11-18-2005, 12:09 AM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM

Tags for this Thread