How passed as an input parameter?

This is a discussion on How passed as an input parameter? within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <stdlib.h> struct product { char code[5]; int year; char country[25]; } ; struct product p; void ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    67

    How passed as an input parameter?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
        struct product
        {
            char code[5];
            int year;
            char country[25];
    
        } ;
    
        struct product p; 
    
        void write();        
        void read();
        void del();
    
        int main(void)
        {
            //write();
            read();    
            del();
        }
    
        void write()
        {
            FILE *file1;
    
            char choice;
    
            file1 = fopen("product.dat", "w");
    
            do
            {
                fflush(stdin);
                printf("Input product code: ");
                scanf("%s", &p.code);
    
                fflush(stdin);
                printf("\nInput product expired year: ");
                scanf("%d", &p.year);
    
                fflush(stdin);
                printf("\nInput product country: ");
                scanf("%s", &p.country);
    
                // Write Records
                fwrite(&p, sizeof(struct product), 1, file1); 
    
                fflush(stdin);
                printf("\nMore product? [Y/N]: ");
                scanf("%c", &choice);
                choice = toupper(choice);
    
                printf("\n");
    
            } while (choice != 'N');
    
            fclose(file1);        
    
        };
    
        void read()
        {
            FILE *file1;
    
            file1 = fopen("product.dat", "r");
    
            if(file1 == NULL)
            {
                printf("\nError open files.");
                exit(0);
            }
            
            // Read Records
            fread(&p, sizeof(struct product), 1, file1); 
    
            printf("\t\tProduct Detail");
            printf("\n\nProduct Code\tExpiry Year\tCountry");
            printf("\n============\t===========\t=======");
    
            while (!feof(file1))
            {    
                printf("\n%s\t\t%d\t\t%s", p.code, p.year, p.country);
    
                fread(&p, sizeof(struct product), 1, file1); 
            }
    
            fclose(file1);
    
            printf("\n\n");
    
        }
    
        void del()
        {
    
        }
    Hi, my question is how can I passed the product year as an input parameter to the delete function after I have scan all data from read function. Because I have to lets user search the product year then user will able to delete the product based on the product year they search.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    There are multiple solutions to the problem...

    For small files, a "linear search" is good enough. Just read each record in turn and compare years.

    For larger files, you would extract an index by reading the large file, creating a smaller file of record numbers by year and sort the index by years so that you can use a "binary search" algorythm to speed up searching.

    In most records based files you don't actually remove the record, you mark it as deleted either with a special Active variable or you place an invalid data in a known location ... eg Product # = -1; then you periodically make a single pass rewriting the file to a copy but skipping over flagged records... read record, is it flagged, no? write record... when done delete the original file and rename the copy.

    Of course there are lots of other options you can use...

    To give you something of an example of records based or "random access" filing, copy/paste this and play with it.
    Code:
    //random access file demo
    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>
    #include <ctype.h>
    #include <string.h>
    
    #define FNAME "random.dat"
    
    // test data struct
    struct t_Record
      { int number;
        char word[16]; }
      Record;
    
    
    
    ///////////////////////////////////////////////////////
    // Random Access File Handlers
    //
    
    // open or create the file
    FILE *FileOpen(char* Filename)
      { FILE* pFile;
        pFile = fopen(Filename,"rb+");
        if (!pFile)
          pFile = fopen(Filename,"wb+");
        return pFile; }
    
    
    // Write a record to the file
    int WriteRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fwrite(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    // read a record from the file
    int ReadRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fread(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    int AddRecord(FILE *File)
      { fseek(File,0,SEEK_END);
        fwrite(&Record,sizeof(Record),1,File);
        return (ftell(File) / sizeof(Record)) - 1; }
    
    
    
    //////////////////////////////////////////////////////////////
    // View a Record
    //
    
    int ViewRecord (FILE *File, int RecNum)
      { if (! ReadRecord(File,RecNum))
          { printf("Invalid record\n"); 
            return -1; }
        printf("-----\n");
        printf("Record        : %d\n",RecNum);
        printf("Number Value  : %d\n",Record.number);
        printf("Word Value    : %s\n",Record.word);
        printf("-----\n");  
        return RecNum; }
    
    
    
    //////////////////////////////////////////////////////////////
    // Add a new record
    //
    
    int AddNewData(FILE *File)
      { memset(&Record,0,sizeof(Record));
        printf("\nEnter a number : ");
        scanf("%d", &Record.number);
        printf("Enter a word : ");
        scanf(" %s",Record.word);
        return AddRecord(File); }
    
    
    
    //////////////////////////////////////////////////////////////
    // Edit a record
    //
    
    int EditRecord(FILE *File, int RecNum)
      { if (! ReadRecord(File,RecNum))
          { printf("Invalid record\n");  
            return -1; }
        printf("\n-----\n");
        printf("Record        : %d\n",RecNum);
        printf("Number Value  : %d\n",Record.number);
        printf("Word Value    : %s\n",Record.word);
        printf("-----\n");  
        
        do
          { while(getchar() != '\n');
            printf("Change Values: Number, Word or Save (N, W or S) ? ");
            switch (toupper(getchar()))
              { case 'N' :
                  printf("\nEnter new number : ");
                  scanf("%d",&Record.number);
                  break;
                case 'W' : 
                  printf("Enter new word : ");
                  scanf(" %15s", Record.word);
                  break;
                case 'S' :
                  if (WriteRecord(File,RecNum))
                    printf("\nRecord #%d updated\n",RecNum);
                  return RecNum; } }
        while(1);
        return -1; }
    
    
    ////////////////////////////////////////////////////////////////
    // List records
    // 
    
    void ListRecords(FILE *File )
      { int i = 0;
        printf("\nRecord     Number\tWord\n\n");
        while (ReadRecord(File,i))
          { printf("%3d%16d\t%s\n",i,Record.number,Record.word); 
            i++; }
        printf("\n\n"); }
    
    
    
    ////////////////////////////////////////////////////////
    // this is for demonstration purposes only
    // you would not do this in a real program
    void InitFile(FILE* File)
     { int x, y;
       memset(&Record,sizeof(Record),0);
       for (x = 0; x < 10; x++)
          { Record.number = rand();
            for (y = 0; y < ((Record.number % 15) + 1); y++)
              Record.word[y] = (rand() % 26) + 'a';
            Record.word[y] = 0;
            if (! WriteRecord(File,x))
              printf("Oh drat!");  } }
     
    
    
    //////////////////////////////////////////////////////////
    // program mains
    //
    int main (void)
      { int Rec = 0; // record number
        FILE *File;
    
        srand(time(NULL));
    
        File = FileOpen(FNAME); 
        if (!File)
          { printf("Curses foiled again!\n\n");
            exit(-1); }
    
        printf("Random Access File Demonstration\n\n");
     
        do
          { printf("Menu : Dummy, Add, Edit, View, List, Quit (D, A, E, V, L or Q) : ");
            switch(toupper(getchar()))
              { case 'D' :
                  printf("Creating dummy file of 10 entries\n");
                  InitFile(File);
                  break;
                case 'A' :
                  Rec = AddNewData(File);
                  printf("Record #%d Added\n\n", Rec);
                  break;              
                case 'E' :
                  printf("\nRecord number (-1 Cancels): ");
                  scanf("%d",&Rec);
                  if (Rec > -1)
                    EditRecord(File,Rec);
                  break;
                case 'V' :
                  printf("\nRecord number (-1 Cancels): ");
                  scanf("%d",&Rec);
                  if (Rec > -1)
                    ViewRecord(File,Rec);
                  break;
                case 'L' :
                  ListRecords(File);
                  break;
                case 'Q' :
                  fclose(File);
                  return 0; } 
                  
             while(getchar() != '\n'); }
        while (1); 
        return 0; }

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    67
    Wow ~ Thanks for giving me such a wonderful example to play with it But I notice that in this example contain fseek command, and I haven learn this command yet, so I wonder did fseek command is the only way to make this program works or I will able to use other command to replace it?

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Siaw Ys View Post
    Wow ~ Thanks for giving me such a wonderful example to play with it But I notice that in this example contain fseek command, and I haven learn this command yet, so I wonder did fseek command is the only way to make this program works or I will able to use other command to replace it?
    So... look it up in your compiler's library documentation or help files... (Don't have that? Get it!)

    fseek() is necessary to locate the file pointer to the correct location to read or write a struct to disk.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Object passed to method as parameter
    By elodman in forum C# Programming
    Replies: 11
    Last Post: 09-22-2011, 08:59 PM
  2. input parameter debug
    By George2 in forum Windows Programming
    Replies: 1
    Last Post: 07-14-2008, 04:22 AM
  3. print input parameter values
    By George2 in forum Windows Programming
    Replies: 0
    Last Post: 06-30-2008, 04:33 AM
  4. function as a input parameter
    By GaPe in forum C Programming
    Replies: 5
    Last Post: 02-02-2003, 07:05 PM
  5. Comparing A Struct To A Passed Parameter
    By Anonymous in forum C++ Programming
    Replies: 1
    Last Post: 11-09-2002, 11:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21