简体   繁体   中英

File reading in C. Complications with fread function

I'm reading an input file and I am having complications regarding reading each line in it. My input file has two types of records. One has 52 characters while the other has 926. I don't know what to do with my fread function so that it can handle both records. Can anyone help me out? thanks

#define LINESZ 927     /* one extra byte for new line */
int num;               /* integer for line number */
char buffer[LINESZ];   /* buffer for file read line */

int main()
{
    FILE *ifp, *ofp;

    ifp = fopen("dd:INPUTF", "r");
    ofp = fopen("dd:OUTPUTF", "w");

    while (!feof(ifp)) {
        if (num = (fread(buffer, sizeof(char), LINESZ, ifp))) {
            if (buffer[22] == 'O') {
                printf("ravroot, %c\n", buffer[22]);
                printf("%s*\n", buffer);
            }
            else if (buffer[22] == 'A') {
                printf("ravrate, %c\n", buffer[22]);
                printf("%s*\n", buffer);
            }
        }
    }

    fclose(ifp);
    fclose(ofp);
    return(0);
}

When reading lines from a file, you should use the fgets function. Note however, that fgets will write the newline character to your buffer, so you need to strip the newline out. The resulting code looks like this

#define LINESZ 1024    /* lots of extra bytes, memory is cheap */
char buffer[LINESZ];   /* buffer for file read line */

int main( void )
{
    int length;
    FILE *ifp, *ofp;

    ifp = fopen("dd:INPUTF", "r");
    ofp = fopen("dd:OUTPUTF","w");

    while( fgets( buffer, LINESZ, ifp ) != NULL )
    {
        // remove the newline character, if any
        length = strlen( buffer );
        if ( length > 0 && buffer[length-1] == '\n' )
            buffer[--length] = '\0';                    

        if ( length > 22 )
        {
            if(buffer[22] == 'O')
            {
                printf("ravroot, %c\n", buffer[22]);
                printf("%s*\n", buffer);
            }
            else if(buffer[22] == 'A')
            {
                printf("ravrate, %c\n", buffer[22]);
                printf("%s*\n", buffer);
            }
        }
    }
    fclose(ifp);
    fclose(ofp);
    return(0);    
}

If every record is in seperate line thne use the fgets function which will stop when the newline is encountered , eg:

 while(fgets(buf,LINESZ,ifp) != NULL)
 {
     //you can put your code here
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM