great masters, i am in desperate need of help. i have a text file like this:

(employee.txt)
john,a100,1
bob,a200,2
chris,a300,3

i need a very small program that when i enter an employee number(ex. "a200"), it will display the name and number on the same line. thanks.

#include<stdio.h>  //printf,scanf
#include<stdlib.h> //atof,atoi
#include<ctype.h>  //isdigit,isalpha
#include<string.h> //strcmp,strlen,strcpy

void nullFile(FILE *myFile)
{
     printf(" Error 67321: FILE READING ERROR. Exit System...\a\n ");
     system("pause");
     exit(0);
}

int main(void)
{
    FILE *fileReader; //create a stream variable

    fileReader = fopen("employee.txt","r"); //associate variable with a file

    if(fileReader==NULL)
        nullFile(fileReader);

    while(!feof(fileReader))
    {
        char line[BUFSIZ];
        fscanf(fileReader, "%[^\n]\n", line);
        printf("%s\n", line);
    }

    fclose(fileReader); //close the file
getchar();
}

master, i know how to open, read(all) from a textfile, but that just about it. can we "query" the textfile? hail ancient dragon...

sorry, wasnt able to erase some of the headers not needed in the program. stdlib and ctype.

To query a text file you have to read the entire file from start to finsh. Read a line, check if it's the one you are looking for. If it is, then stop reading. Otherwise, if it is not then read the next line.

There is no other way to do it with text files because they have variable length lines.

Binary files would have a much more efficient method of searching.

master, can you give me scrap code on how to check per line,print specified line, and stop. dont know your advice can be implemented. sorry for my ignorance.

You have already written half the program. After line 26 add some code that checks if the line just read is the one you want. If it is, then put in a break statement.

if( this is the line I want )
   break;

ok, ill try it out. sir, after i have located the line i want, how will i print only that line and not from that line to bof? thanks. (ancient dragon==pure knowledge)

Now how do you think you can change the two lines I previously posted so that it also prints out the line before the break statement?


>>ancient dragon==pure knowledge)
Only because I've been doing this sooooo long (about 25 years) :) You'll get there too -- just keep at it.

This article has been dead for over six months. Start a new discussion instead.