how do you search a string from a file using file i/o? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

how do you search a string from a file using file i/o?

confusedlilkidconfusedlilkid Posts: 7Member
this is what i have so far... i don't know how to begin my code for the "search" part.

[code]
int main(void)
{
int i;
student_t eee11[20];
int a=0;
int check1=0;
int check2=0;
FILE *in_file;


while(a!=1||a!=2||a!=3||a!=4){
printf("
[1] Load file
[2] Compute individual average
[3] Compute class average
[4] Exit
[5] Search for a Student
Select a number:");
scanf("%d",&a);
getchar();

switch(a){
case 1:
in_file=fopen("input_corrected.csv", "r");
if(in_file==NULL){
return 1;
}
else{
for (i=0; i<20; i++)
{
eee11[i] = get_student(in_file);
}
}
check1=1;
break;


case 2:
if(check1!=1){
printf("INVALID INPUT!");
break;
}
for (i=0; i<20; i++)
{
eee11[i].average = get_ave(eee11[i]);
printf("The average of %s is %0.2f.
", eee11[i].std_no, eee11[i].average);
printf("press enter to proceed...");
getchar();
}
check2=1;
break;


case 3:
if(check1!=1){
printf("INVALID INPUT!");
break;
}
get_class_ave(eee11, 20);
break;

case 4:
return 0;
fclose(in_file);

case 5:
//insert search code here

default:
printf("Invalid input!
");
a=0;
}
}
}
[/code]

Comments

  • ArkadiArkadi Posts: 6Member
    Just equivalent code that is human readable.

    [code]
    int main(void)
    {
    int i;
    student_t eee11[20];
    int a=0;
    int check1=0;
    int check2=0;
    FILE *in_file;

    while(true) {
    printf(
    "
    "
    " [1] Load file
    "
    " [2] Compute individual average
    "
    " [3] Compute class average
    "
    " [4] Exit
    "
    " [5] Search for a Student
    "
    "Select a number:");
    scanf("%d
    ",&a);

    switch(a){
    case 1:
    in_file=fopen("input_corrected.csv", "r");
    if(in_file==NULL)
    return 1;
    for (i=0; i<20; i++)
    eee11[i] = get_student(in_file);
    check1=1;
    break;
    case 2:
    ...
    [/code]

    Still, the code above don't make any sense, unless you are targeting a specific data handling.
    From here on you have somewhat unlimited number of choices:
    a. Read each time all the file line by line: fgets, strstr(to find delimiter)
    b. Read all the file into memory
    - Store as is in a string
    - Cut into fields and manage two-dimensional array
    - Cut into fields and store array of structures
    c. Employ Lex to cut delimiters
    d. Employ ODBC with CSV driver
    ...

    Notice that scanf is not good enough for production tools - you can't predict what garbage your user will put in.

Sign In or Register to comment.