1

I have a program that I am trying to write that will open a file named list.txt, this file will contain a num, a ID, and a string name on each line. This program will read list.txt file and sort ID numbers and print sorted ID with number and name to index.txt file. I wrote a program code and it's working...

Here is my list.txt

(num, ID, name)

0 3 AB
1 2 BC
2 28 DC
3 1 EF
4 13 BB
10 30 CC
11 23 FF
14 16 GG

After compiled this program sorted ID with number and name, print to index.txt and it should be:

(ID, num, name)

1 3 EF
2 1 BC
3 0 AB
13 4 BB
16 14 GG
23 11 FF
28 2 DC
30 10 CC

Here is my program code:

#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <stdlib.h>
#include <string.h>

#define NUM_NUMBERS 9

typedef struct student
{   
    int num;
    int id;
    char name[100];
}end;

void update();
void Sort(student array[], int n); 
void load_menu();
void add(end *e);
void search(end e);
void view(end e);

FILE *fp;
FILE *f1;

int main(int argc, char** argv)
{

    load_menu();

    return 0;
}
void update()
{
    end st[15];
    int sayi[NUM_NUMBERS], number, i=0, j=0;
    fp=fopen("list.txt", "r");
    if( fp == NULL ) 
    {
        printf("File is not found at add();\n");
        exit(0);
    }
    while(!feof(fp))
    {
        fscanf(fp,"%d%d%s",&st[i].num,&st[i].id,st[i].name);
        i++;
    }
    Sort(st, NUM_NUMBERS);
    f1=fopen("index.txt", "w");
    for(int i=0; i<NUM_NUMBERS;i++)
    {
        fprintf(f1, "%d %d %s\n", st[i].id, st[i].num, st[i].name);
    }
}
void Sort(end array[], int n)
{
    int Min;
    for(int i=0; i<n-1;i++)
    {
        Min=i;
        for(int j=i+1;j<n;j++)
        {
            if(array[j].id<array[Min].id)
            {
                Min=j;
            }
        }
        end temp=array[i];
        array[i]=array[Min];
        array[Min]=temp;
    }
}
void load_menu(void)
{
    end e; 
    int choice;
    do
    {
        printf("1. Find a record given its ID value \n");
        printf("2. Add a new record to the file \n");
        printf("3. View Records\n");
        printf("4. Exit\n\n");
        printf("Please choose one: ");
        scanf("%d",&choice);
        switch(choice)
        {
            case 1:
                search(e);
                break;
            case 2: add(&e);
                    update();
                break;
            case 3: view(e);
                break;
            case 4: printf("Done.");
                return;
                break;
            default: printf("Invalid choice\n");
        }
    }while (choice != 5);
    system("cls");
} 
void add(end *e)
{
    int i=0;
    system("cls");
    fp = fopen ( "list.txt", "a" );
    if( fp == NULL ) 
    {
        printf("File is not found at add();\n");
        exit(0);
    }
    printf("\n-----Add a new record-----\n");
    printf("Enter number: ");
    scanf("%d", &e->num);
    printf("\nEnter ID : ");
    scanf("%d",&e->id);
    printf("\nEnter name: ");
    scanf("%s",e->name);
    fscanf(fp,"%d %d %s\n\n",&e->num, &e->id, e->name);
    fprintf(fp,"%d %d %s\n\n",e->num ,e->id, e->name);
    fclose(fp);
    return;
}
void search(end e)
{
    int i=0;
    int sid;
    system("cls");
    fp = fopen ("list.txt", "r");
    if(fp==NULL)
    {
        printf("File is not found at search();");
    }
    printf("\n-----Search ID-----\n");
    printf("\nEnter ID : ");
    scanf("%d",&sid);
    printf("\nNumber   ID       Name");
    while(!feof(fp))
    {
        fscanf(fp,"%d %d %s", &e.num, &e.id, &e.name);
        if(sid==e.id)
        {   
            printf("\n%d        %d        %s",e.num ,e.id, e.name);
        }
    }
    printf("\n\n");
    fclose(fp);
}
void view(end e)
{
    int i=0;
    system("cls");
    printf("\n-----list.txt-----\n");
    fp = fopen("list.txt", "r");
    if(fp == NULL)
    {
        printf("File is not found at view();\n");
        exit(0);
    }
    printf("\nNumber   ID       Name");
    printf("\n");
    while(fscanf (fp, "%d %d %s ",&e.num, &e.id, &e.name) != EOF )
    printf("\n%d        %d        %s",e.num ,e.id, e.name);
    printf("\n\n");

    printf("-----index.txt-----\n");
    f1 = fopen("index.txt", "r");
    if(fp == NULL)
    {
        printf("File is not found.\n");
        exit(0);
    }
    printf("\nNumber   ID       Name");
    printf("\n");
    while(fscanf (f1, "%d %d %s ",&e.id, &e.num, &e.name) != EOF )
    printf("\n%d        %d        %s",e.id ,e.num, e.name);
    printf("\n\n");

    fclose(fp);
    fclose(f1);
    return;
}

But I used only array so I need to dynamically allocate at array of struct to store the info. Still don't know how to use dynamically allocate (malloc). Could you please show me how to use dynamically with code? Thanks for helps. (Sorry for bad english.)

5
  • 1
    Even though you are using C functions, you are actually programming in C++. Commented Dec 9, 2016 at 10:39
  • 3
    Also please read Why is “while ( !feof (file) )” always wrong? Commented Dec 9, 2016 at 10:39
  • It's c++, no c, why stuck with old data structures? Use std::vector. Commented Dec 9, 2016 at 10:44
  • Sorry I posted wrong code, edited. Commented Dec 9, 2016 at 11:54
  • at add : fscanf(fp,"%d %d %s\n\n",&e->num, &e->id, e->name); Delete this. Commented Dec 9, 2016 at 18:08

2 Answers 2

1

sample code:

#include <stdio.h>
#include <stdlib.h>

typedef struct student{   
    int num;
    int id;
    char name[100];
}end;

int cmp(void const *a, void const *b){
    const end *x = a;
    const end *y = b;
    return x->id < y->id ? -1 : x->id > y->id;
}

int main(void){
    end *st = NULL, tmp;
    FILE *fp;
    size_t i = 0, n = 0;

    fp=fopen("list.txt", "r");
    if( fp == NULL ) {
        perror("fopen at XXX");
        exit(EXIT_FAILURE);
    }
    while(3 == fscanf(fp,"%d %d %s", &tmp.num, &tmp.id, tmp.name)){
        end *temp = realloc(st, ++n * sizeof(*st));//Secure multiple records when the number of records is large
        if(temp == NULL){
            perror("realloc at XXX");
            free(st);
            exit(EXIT_FAILURE);
        }
        st = temp;
        st[i++] = tmp;
    }
    fclose(fp);

    qsort(st, n, sizeof(*st), cmp);

    fp=fopen("index.txt", "w");
    for(i = 0; i < n; ++i){
        fprintf(fp, "%d %d %s\n", st[i].id, st[i].num, st[i].name);
    }
    fclose(fp);
    free(st);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for answer and help but there are some error at int cmp(void const *a, void const *b){ const end *x = a; const end *y = b; return x->id < y->id ? -1 : x->id > y->id; }
@ArkhamKnight I think that I am not wrong. Why do you think it is a mistake?
No, absolutely you are right, your code is true but Visual Studio says 'initializing': cannot convert from 'const void *' to 'const end *'
@ArkhamKnight It seems to be because you are using C++ as C. Please cast as follows. const end *x = (const end *)a; const end *y = (const end *)b;
Silly me, I forgot rename Source.cpp to Source.c. Thank you very much, I think it's working, now I will write add(), search() etc. functions. Thanks for all efforts.
0

malloc() returns a pointer to the memory you allocated. The argument is the size of the memory you want to allocate, so in your case its the size of of "end".

You need to declare a pointer to "end" first and then call malloc().

end * ptr = malloc(sizeof(end));

But thats just one Element. You should definitely check out a tutorial for lists in c.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.