[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Need help for writing and reading binary to linked list

Posted on 2011-04-21
29
Medium Priority
?
373 Views
Last Modified: 2012-05-11
Hello, I would need some help to build working function for writing and reading binary to linked list. I think my writing part is working, but I don't know how to code the read part, but I have guide for it.
1. Copy from binary new ptr(?)
2. Where to add (where in list, beginning or after..)
3. Add
4. New round

struct:

struct linked_list
{
    struct linked_list *previous;
    int ark_nro;          
    char name[100];        
    struct linked_list *next;  /** Tallentaa seuraavan alkion osoitteen **/
    int luku;
};

and a little bit of code:

typedef struct linked_list ptr;

void input(ptr*);     /** Inputing information
void add_to_end(ptr*);  /** Adding to the end
ptr* add_before(ptr*); /** Adding before
ptr* del(ptr*);     /** Deleting
void print(ptr*);     /**Printing
void write_bin(ptr*); /** Writing binary
void read_bin(ptr*); /** Reading binary

int main()
{
    ptr *head;
   if choose==6{
  write_bin(head)

Writing and reading functions:
void write_bin(ptr *nykyinen)
{
    FILE *Tiedosto;
    if ((Tiedosto = fopen ("binaaridata.dat", "wb")) == NULL)
    {
        printf ("Tiedostoa \"binaaridata.dat\" ei voitu avata kirjoittamista varten.\n");
        exit (1);
    }

    while(nykyinen!=NULL)
    {
            fwrite(&nykyinen->ark_nro, sizeof(int), 1, Tiedosto);
            fwrite(&nykyinen->nimi, sizeof(char), 1, Tiedosto);
            nykyinen=nykyinen->seuraava;
    }
    fclose(Tiedosto);
}
void read_bin(solmu *beginning) - READ FROM FILE
{

    FILE *Tiedosto;
    ptr *read, *newptr;
    ptr=(ptr*)malloc(sizeof(ptr));

    if ((Tiedosto = fopen ("binaaridata.dat", "wb")) == NULL)
            {
                 printf ("Tiedostoa \"binaaridata.dat\" ei voitu avata lukemista varten.\n");
                 exit (1);
            }

    while(fread(&read, sizeof(ptr), 1, Tiedosto))
    {
        newptr=(ptr*)malloc(sizeof(ptr));

Thank you already and sorry for this long message, but I hope you guys can help me with this one.

Yours,

ljoshak
0
Comment
Question by:ljoshak
  • 17
  • 12
29 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 35440860
You should try compiling your code to start with. It will show a LOT of problems that you can fix by carefully analyzing the error and warning messages you get, and fixing them one at a time.

Once you have code that compiles, please post it back here, and we can assist you further :) Of course, if you have any questions about or problems with any of the error or warning messages you get, feel free to ask here.

Finally, one initial remark on reading data from a file : you want to open the file in "rb" mode (ie. for reading), not "wb" (which is for writing).
0
 

Author Comment

by:ljoshak
ID: 35441154
My code is working well when i run it, but only thing i can't get to work is reading from  binary, which I don't know how to make. Can you give me some information on where to begin? And is my writing to binary working correctly?
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35441210
>> My code is working well when i run it

Then I'm sure that the code you posted here isn't the exact code that you are using ...

Can you please post the exact and complete code that you are using ? (you can attach the source file(s) to your post if you want)
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:ljoshak
ID: 35441272
Here you go, it's in finnish, but i hope you can get the main point. If not then just tell me :)

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

struct linkitetty_lista
{
    struct linkitetty_lista *edellinen;  /** Tallentaa edellisen alkion osoitteen **/
    int ark_nro;             /** Tallentaa arkistonumeron **/
    char nimi[100];            /** Tallentaa nimen **/
    struct linkitetty_lista *seuraava;  /** Tallentaa seuraavan alkion osoitteen **/
    int luku;
};

/** Määritellään linkitetty_lista alkioksi **/
typedef struct linkitetty_lista solmu;

void tieto_sisaan(solmu*);     /** Input -funktio (tietoa sisään) **/
void lisaa_loppuun(solmu*);  /** Funktio, jonka avulla lisätään loppuun **/
solmu* lisaa_eteen(solmu*); /** Funktio, jonka avulla lisätään halutun paikan taakse **/
solmu* del(solmu*);     /** Funktio, jonka avulla poistetaan haluttu alkio **/
void tulostus(solmu*);     /** Funktio, jonka avulla tulostetaan haluttu alkio **/
void etsi_arknro(solmu*); /** Funktio, jonka avulla etsitään haluttu alkio arkistonumeron avulla **/
void kirjoitus_tiedostoon(solmu*); /** Funktio, jolla kirjoitetaan binaaridataa**/
void vapautus(solmu*); /** Vapautetaan muisti **/
void luku_tiedostosta(solmu*); /** Luetaan tiedostosta binaaridata **/
void csv_tallennus(solmu*); /** tallennus csv-muodossa **/

int main()
{
    solmu *head;
    int valikko;
    int menu_valinta=0;
    int valinta=0;
    head=(solmu*)malloc(sizeof(solmu));
    head->seuraava=NULL;
    head->edellinen=NULL;
    while (menu_valinta==0)
    {
        printf("(1) Lisää tieto (loppuun)\n(2) Tarkastele tietoja\n(3) Lisää tieto eteen\n(4) Poista tieto\n(5) Etsi tieto\n(6) Kirjoita tiedostoon\n(7) Lataa tiedostosta\n(8) Kirjoita SVN-tiedosto\n(0) Lopeta\n> ");
        scanf("%d",&valikko);
        if(valikko==1 && valinta==1){
            lisaa_loppuun(head);
            }
        else if (valikko==1 && valinta==0){

            tieto_sisaan(head);
            valinta=1;
            }
        if(valikko==2){
        tulostus(head);
        }
        if(valikko==5){
        etsi_arknro(head);
        }
        if(valikko==3){
            head=lisaa_eteen(head);
        }
        if(valikko==4){
            head=del(head);
        }
        if(valikko==8)
        {
            csv_tallennus(head);
        }
        if(valikko==0){
        vapautus(head);
        menu_valinta=1;
        }
        if(valikko==7)
        {
            //luku_tiedostosta(head);
            valinta=1;
        }
        if(valikko==6)
        {
            kirjoitus_tiedostoon(head);
        }
    }
        return 0;
        }

void csv_tallennus(solmu *nykyinen)
{
    char tiedosto_nimi[21];
      FILE *avaus;
      printf("Anna kirjoitettavan tiedoston nimi (max 20 merkkiä): ");
      scanf("%s", tiedosto_nimi);

      if((avaus = fopen(tiedosto_nimi, "w"))==NULL){
            printf("Tiedoston avaaminen epäonnistui. Lopetetaan..");
            exit(1);
      }else{
            fprintf(avaus,"Arkistonumero\tNimi\n");
            while (nykyinen) {
                    fprintf(avaus, "%d\t%s",nykyinen->ark_nro,nykyinen->nimi);
                    nykyinen=nykyinen->seuraava;
              }
      }
      fclose(avaus);
}

void tieto_sisaan(solmu *nykyinen)
{
    char luku2[20];
int luku1;
    nykyinen->edellinen=NULL;
getchar(); // Tyhj. muisti.
    printf("Anna henkilön arkistonumero\n> ");
fgets(luku2, 20, stdin); // Sen takia char, koska tulee muuten warning: passing argument 1 of fgets makes pointer from integer without a cast??
luku1 = atoi(luku2);
    if(luku1 < 0){
    printf("arkistonumero negatiivinen.\n");
    }
    if(luku1 > 0){
        nykyinen->ark_nro = luku1;
    printf("\nHenkilön arkistonumero %d tallennettu tietokantaan.\n", luku1);
    printf("\nSyötä henkilön nimi.\n> ");
    fgets(nykyinen->nimi, sizeof(solmu), stdin);
    nykyinen->seuraava=NULL;
    printf("\n");
    }

}

void lisaa_loppuun(solmu *nykyinen)
{
    solmu *uusisolmu;
    uusisolmu=(solmu*)malloc(sizeof(solmu));
    tieto_sisaan(uusisolmu);
    while(nykyinen->seuraava!=NULL)
    {
        nykyinen=nykyinen->seuraava;
    }
    {
        /***  Mennään viimeiseen solmuun  ***/
        uusisolmu->seuraava=nykyinen->seuraava;
        nykyinen->seuraava=uusisolmu;
}}

void tulostus(solmu *nykyinen)
{
    printf("NUMERO    NIMI\n");
    while(nykyinen!=NULL)
    {
            printf("%d\t  %s\n",nykyinen->ark_nro,nykyinen->nimi);
            nykyinen=nykyinen->seuraava;
    }
}
void vapautus(solmu *nykyinen)
{
    solmu *valiaikainen;
    while(nykyinen!=NULL)
    {
        valiaikainen = nykyinen->seuraava;
        free(nykyinen);
        nykyinen=valiaikainen;
    }
}

solmu* lisaa_eteen(solmu *nykyinen)
{
    int arknro;            /* arknro josta luodaan solmu */
    solmu *uusisolmu,*valiaikainen;
    uusisolmu=(solmu*)malloc(sizeof(solmu));
    printf("\nAnna sen henkilön arkistonro, jonka eteen haluat nykyisen henkilön lisättävän.\n");
    scanf("%d",&arknro);
    tieto_sisaan(uusisolmu);
    if(nykyinen->ark_nro==arknro)
    {
        /*** Ensimmäisen solmun "tilalle" ***/
        uusisolmu->seuraava=nykyinen;
        nykyinen->edellinen=uusisolmu;
        nykyinen=uusisolmu;
        return(nykyinen);
    }
    valiaikainen=nykyinen;
    while(valiaikainen->seuraava!=NULL)
    {
        /*** Käydään läpi muut solmut paitsi ei ekaa ***/
        if(valiaikainen->seuraava->ark_nro==arknro)
        {
            uusisolmu->seuraava=valiaikainen->seuraava;
            valiaikainen->seuraava->edellinen=uusisolmu;
            valiaikainen->seuraava=uusisolmu;
            uusisolmu->edellinen=valiaikainen;
            return(nykyinen);
        }
        valiaikainen=valiaikainen->seuraava;
    }
    /*
    Jos mikään solmuista ei käsittänyt kyseistä arkistonumeroa, ilmoitetaan, ettei sitä löydy tietokannasta.
    */
    printf("\nArkistonumeroa ei löytynyt.\n");
    return(nykyinen);
}

solmu* del(solmu *nykyinen)
{
    int arknro;               /* arkistonro joka halutaan tuhota*/
    solmu *uusisolmu,*valiaikainen;
    printf("\nAnna sen henkilön arkistonumero, joka halutaan tuhota.\n");
    scanf("%d",&arknro);
    uusisolmu=nykyinen;
    if(nykyinen->ark_nro==arknro)
    {
        /***  Tarkastetaan eka solmu  ***/
        uusisolmu=nykyinen;
        nykyinen=nykyinen->seuraava;
        nykyinen->edellinen=NULL;
        free(uusisolmu);
        return(nykyinen);
    }
    else
    {
        while(uusisolmu->seuraava->seuraava!=NULL)
        {
            /***  Katsotaan kaikki muut, paitsi ensimmäinen ja viimeinen solmu ***/
            if(nykyinen->seuraava->ark_nro==arknro)
            {
                uusisolmu=nykyinen;
                valiaikainen=nykyinen->seuraava;
                uusisolmu->seuraava=uusisolmu->seuraava->seuraava;
                uusisolmu->seuraava->edellinen=nykyinen;
                free(valiaikainen);
                return(nykyinen);
            }
            uusisolmu=uusisolmu->seuraava;
        }
        if(uusisolmu->seuraava->seuraava==NULL && uusisolmu->seuraava->ark_nro==arknro)
        {
            /***  Tarkistetaan viimeinen solmu ***/
            valiaikainen=uusisolmu->seuraava;
            free(valiaikainen);
            uusisolmu->seuraava=NULL;
            return(nykyinen);
        }
    }
    printf("\nPuhelinnumeroa ei löytynyt tietokannasta.\n");
    return(nykyinen);
}

void etsi_arknro(solmu *nykyinen)
{
    int arknro;
    printf("\nAnna haettavan käyttäjän arkistonumero\n");
    scanf("%d",&arknro);
    while(nykyinen->seuraava!=NULL)
    {
        if(nykyinen->ark_nro==arknro)
            printf("\n%d\t%s\n",nykyinen->ark_nro,nykyinen->nimi);
        nykyinen=nykyinen->seuraava;
    }
    if(nykyinen->seuraava==NULL && nykyinen->ark_nro==arknro)
        printf("\n%d\t%s\n",nykyinen->ark_nro,nykyinen->nimi);
}

void kirjoitus_tiedostoon(solmu *nykyinen)
{
    FILE *Tiedosto;
    if ((Tiedosto = fopen ("binaaridata.dat", "wb")) == NULL)
    {
        printf ("Tiedostoa \"binaaridata.dat\" ei voitu avata kirjoittamista varten.\n");
        exit (1);
    }

    while(nykyinen!=NULL)
    {
            fwrite(&nykyinen->ark_nro, sizeof(int), 1, Tiedosto);
            fwrite(&nykyinen->nimi, sizeof(char), 1, Tiedosto);
            nykyinen=nykyinen->seuraava;
    }
    fclose(Tiedosto);
}
void luku_tiedostosta(solmu *alku) // Not Working!
{

    FILE *Tiedosto;
    solmu *luettu, *uusisolmu;
    solmu=(solmu*)malloc(sizeof(solmu));

    if ((Tiedosto = fopen ("binaaridata.dat", "wb")) == NULL)
            {
                 printf ("Tiedostoa \"binaaridata.dat\" ei voitu avata lukemista varten.\n");
                 exit (1);
            }

    while(fread(&luettu, sizeof(solmu), 1, Tiedosto))
    {
        uusisolmu=(solmu*)malloc(sizeof(solmu));

        /* Copy read to new ptr
         * into what list?
         *add
         * new round
         */

        /*

}
}
0
 

Author Comment

by:ljoshak
ID: 35441282
Check the end, like, writing to binary and reading from binary, everything else is working if you enter correct values.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35441374
Start by making the change I suggested earlier : ie. use the mode "rb" to read from a file.

Next, you'll want to use fread correctly. You're passing it the address of a pointer to a solmu object (so, a pointer-to-pointer-to-solmu) as first argument. But you're actually trying to read a solmu object from the file, which would mean you'd need a pointer-to-solmu as the first argument of fread.

You could pass luettu, since it has the correct type (solmu*), but then you'd first have to allocate some memory, so the pointer actually points somewhere.
Or you could make luettu an object of type solmu, and pass its address as first argument to the fread function.
0
 

Author Comment

by:ljoshak
ID: 35441678
Sorry Sir but for some reason I don't just get it. Can you give me examples or open this a little bit more?
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35441749
Do you understand what the second parameter of the fopen function is for ? It specifies the mode for opening the file. Please have a look at this reference page for a more detailed description :

        http://www.cplusplus.com/reference/clibrary/cstdio/fopen/


Do you understand the distinction between a solmu** (pointer-to-pointer-to-solmu) and a solmu* (pointer-to-solmu) ?
Do you understand what the first parameter of the fread function is for ? It specifies the memory location in which the data that is read from the file should be placed. Please have a look at this reference page for a more detailed description :

        http://www.cplusplus.com/reference/clibrary/cstdio/fread/
0
 

Author Comment

by:ljoshak
ID: 35442221
I know pointer-to-solmu, but really don't understand pointer-pointer is (checked out http://www.codeproject.com/KB/cpp/PtrToPtr.aspx#3 also some uni dias about that but still I didn't understand it), I'd like to make a prototype that prints out what it read from the binary file, and I read that link you gave me, but how I can get from this


  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "binaaridata.dat" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

to print the same things out? (like print("%d, %s", &result->ark_nro, &result->name) ?)
It just prints me the pointer (right?) ? printing %d &result gives me the memory, right?
All this binary is so weird rly, but hoping to get this done one way or another :)
0
 

Author Comment

by:ljoshak
ID: 35442630
Okay, Now I tried something:
void luku_tiedostosta(solmu *alku)
{

FILE *avaus;
      avaus = fopen("binaaridata.dat", "rb");
          if (!avaus){
            printf("Virhe! Lopetetaan..");
            exit(1);
      }else{
            while(alku){
                  fread(&alku->ark_nro, sizeof(int), 1, avaus);
                  fread(&alku->nimi, sizeof(long), 1, avaus);
                  printf("%d, %s\n", alku->ark_nro, &alku->nimi);
                  alku=alku->seuraava;
            }
      }
      fclose(avaus);
}
it prints only the first ark_nro (which is 1) and the first letter of first name (Which is K in my binary)...
any comments?
0
 

Author Comment

by:ljoshak
ID: 35443833
Don't know how to edite my comments, so I have one question:

     while(alku){
                  fread(&alku->ark_nro, sizeof(int), 1, avaus);
                  fread(&alku->nimi, sizeof(long), 1, avaus);
                  printf("%d, %s\n", alku->ark_nro, &alku->nimi);
                  alku=alku->seuraava;

while(alku) is not working correctly, so what to use for reading binary? while(enter here!)
and, how can I read whole sentence, not just first letter of &alku->nimi? what else.. hmm..
And yes, how to save it to new pointer? if alku is the one that saves all data every round so I must save it to some ptr (maybe uusisolmu and then use that one)?
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35446057
>> while(alku) is not working correctly,

It would only work correctly if you already have all nodes in the linked list, and just need to fill them.
Presumably though, you'll want to add NEW nodes to the linked list when you read data from the file ?


>> and, how can I read whole sentence, not just first letter of &alku->nimi?

nimi is an array of 100 char's, but you're trying to read a long from the file :

>>                   fread(&alku->nimi, sizeof(long), 1, avaus);

Instead you'll want to read 100 char's from the file. Have a closer look at the meaning of the second and third parameters to fread (see the reference page I posted earlier).

In your write function you do it almost correctly, but there is one problem with it :

>> fwrite(&nykyinen->nimi, sizeof(char), 1, Tiedosto);

Yo're only writing 1 char to the file. You probably should be writing all 100 char's to the file. Then you'd be able to read all 100 char's back from the file.
0
 

Author Comment

by:ljoshak
ID: 35446846
Hi Sir, Your help has been so good so far :)

But still one more, Now my code looks like this:

{
            while(uusisolmu){
                  fread(&uusisolmu->ark_nro, sizeof(int), 1, avaus);
                  fread(&uusisolmu->nimi, sizeof(char), 100, avaus);
                  nykyinen->ark_nro=uusisolmu->ark_nro;
                  strncpy(nykyinen->nimi, uusisolmu->nimi, sizeof(uusisolmu->nimi));
                  printf("%d, %s\n", nykyinen->ark_nro, &nykyinen->nimi);
                  nykyinen->seuraava=NULL;
            }

And it is working (printing correctly), BUT the while loop is going for eeveer... so there must be something wrong and I really dont understand what is it.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35446856
>> BUT the while loop is going for eeveer... so there must be something wrong and I really dont understand what is it.

Notice that the loop condition is using uusisolmu, but you're never changing uusisolmu inside the loop.
0
 

Author Comment

by:ljoshak
ID: 35446889
Hmm Now I see, but I have no idea how to cut it? How do I know when It has read the whole file etc..?
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35446901
>> How do I know when It has read the whole file etc..?

You can check whether the end of the file has been reached by using feof :

        http://www.cplusplus.com/reference/clibrary/cstdio/feof/
0
 

Author Comment

by:ljoshak
ID: 35447973
Okay that was helpful as well, but I have one problem more to finish this code:

            while(!feof(avaus)){
            nykyinen->edellinen=NULL;
                  fread(&alku->ark_nro, sizeof(int), 1, avaus);
                  fread(&alku->nimi, sizeof(char), 100, avaus);
                  nykyinen->ark_nro=alku->ark_nro;
                  strncpy(nykyinen->nimi, alku->nimi, sizeof(alku->nimi));
                  nykyinen->seuraava=NULL;
            }

When printing it out (going to the main menu and pressing 2), it only prints me the last data (last number and last name), so how can I point it out to the first memory block? And If I can't how should I edit my code? :)
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35447996
Make sure that you insert a NEW node into the linked list for every record that you read from the file. Right now, it looks like you're always overwriting the same node.
0
 

Author Comment

by:ljoshak
ID: 35448172
while(!feof(avaus)){
                if(aloitus==0){
            nykyinen->edellinen=NULL;
                  fread(&alku->ark_nro, sizeof(int), 1, avaus);
                  fread(&alku->nimi, sizeof(char), 100, avaus);
                  nykyinen->ark_nro=alku->ark_nro;
                  strncpy(nykyinen->nimi, alku->nimi, sizeof(alku->nimi));
                  nykyinen->seuraava=NULL;
                }
                else if(aloitus!=0){
                uusisolmu->edellinen=NULL;
                fread(&alku->ark_nro, sizeof(int), 1, avaus);
                  fread(&alku->nimi, sizeof(char), 100, avaus);
                  uusisolmu->ark_nro=alku->ark_nro;
                  strncpy(uusisolmu->nimi, alku->nimi, sizeof(alku->nimi));
                  uusisolmu->seuraava=NULL;
                  while(nykyinen->seuraava!=NULL)
            {
            nykyinen=nykyinen->seuraava;
            }
            uusisolmu->seuraava=nykyinen->seuraava;
            nykyinen->seuraava=uusisolmu;
            }
            aloitus=1;
            }

This is what I tried to do: First off: It reads 2 times the first binary lines (first data twice), why? And It makes some kind of loop when trying to print it out by pressing 2, I don't really know if it only prints out the last data. The code is taken from functions tieto_sisaan(head) which makes the first pointer, and after that lisaa_eteen(head) which adds new node to the first one.
0
 

Author Comment

by:ljoshak
ID: 35448583
Okay so

void tulostus(solmu *nykyinen)
{
    printf("NUMERO    NIMI\n");
    //while(nykyinen!=NULL)
    //{
            printf("%d\t  %s\n",nykyinen->ark_nro,nykyinen->nimi);
            nykyinen=nykyinen->seuraava;
            printf("%d\t  %s\n",nykyinen->ark_nro,nykyinen->nimi);
    //}
}

When i print like this, I can get the data right, but if i put nykyinen!=NULL it makes a loop that never ends, so it seems that nykyinen never gets NULL.. so How can I fix that? :)
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35449372
It would probably be more convenient to have a few helper functions. For example :

(a) a function that takes the node data members as parameters (ie. ark_nro and nimi), and constructs a node with those data members.

(b) a function that takes the linked list as the first argument, and a pointer to a new node as the second argument. The function would then add that node into the linked list.

Using these functions in the appropriate locations (in lisaa_eteen eg., as well as in your luku_tiedostosta function), will make things a lot easier to manage.
0
 

Author Comment

by:ljoshak
ID: 35450148
Hi, I got it working now but I had to make one solution and I think the problem is in the while loop:

while(!feof(avaus)){
                if(aloitus==0){
                    nykyinen->edellinen=NULL;
                fread(&alku->ark_nro, sizeof(int), 1, avaus);
                fread(&alku->nimi, sizeof(char), 100, avaus);
                nykyinen->ark_nro=alku->ark_nro;
                strncpy(nykyinen->nimi, alku->nimi, sizeof(alku->nimi));
                printf("%d %s", nykyinen->ark_nro, nykyinen->nimi);
                nykyinen->seuraava=NULL;
                aloitus=1;
                }
                  else if(aloitus==1){
                      // Se lukee ekana päälle ton.. hmm..
                      //joten fread kahesti?
                      if(silmukka==0){
                          // Tän takia toimii kunnolla, emt miten vois välttää?
                          fread(&alku->ark_nro, sizeof(int), 1, avaus);
                fread(&alku->nimi, sizeof(char), 100, avaus);
                silmukka=1;
                      }
                      else if(silmukka==1){
                fread(&alku->ark_nro, sizeof(int), 1, avaus);
                fread(&alku->nimi, sizeof(char), 100, avaus);
                uusisolmu->ark_nro=alku->ark_nro;
                strncpy(uusisolmu->nimi, alku->nimi, sizeof(alku->nimi));
                printf("%d %s", uusisolmu->ark_nro, uusisolmu->nimi);
                uusisolmu->seuraava=NULL;
                    while(nykyinen->seuraava!=NULL)
    {
        nykyinen=nykyinen->seuraava;
    }

        /***  Mennään viimeiseen solmuun  ***/
        uusisolmu->seuraava=nykyinen->seuraava;
        nykyinen->seuraava=uusisolmu;
        }}
                  }
                }

My comments there: When aloitus==1 (not the first data to read to the pointer, after that ones), it reads everything twice (with fread), so it doesn't work correctly for some reason? Can you spot it? But Like there I have 2 data on my binary file (2 names and 2 numbers) and I had to make this:

 if(silmukka==0){
                          //
                          fread(&alku->ark_nro, sizeof(int), 1, avaus);
                                fread(&alku->nimi, sizeof(char), 100, avaus);
                                silmukka=1;
To read the "twice data".. and then save it to the pointer, and then save that pointer to the original pointer.
0
 

Author Comment

by:ljoshak
ID: 35450398
Oh, It seems now that it reads the LAST DATA TWICE for some reason (or writes it twice too?)?

So is here any problems while(!feof(avaus))

or how can I make that one to read everything else but not the last data?(if it reads it twice).. if you can see the point I am trying to make. :)
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35450415
>> Hi, I got it working now but I had to make one solution

That's a lot of code. Why not take my earlier advice and write some helper functions to make your life easier ? It'll make the code easier to read, will avoid that you have to repeat the same code over and over again, and will help you introduce less bugs.


>> Oh, It seems now that it reads the LAST DATA TWICE for some reason (or writes it twice too?)?

The problem is that the eof flag is set when it tries to read PAST the end of the file.
After every fread, you need to check if it succeeded (by checking its return value), and if not, end the loop.
0
 

Author Comment

by:ljoshak
ID: 35450470
And how do I do that? http://www.cplusplus.com/reference/clibrary/cstdio/feof/ doesn't really help me that much :o
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 2000 total points
ID: 35450490
By checking the return value of fread ... If it returns a value that is not the same as the count value you passed as third parameter, then reading failed, and you've either reached the end of the file, or some other error occurred. Either way : if that happens, you should end the loop immediately (you can use break eg.).
0
 

Author Comment

by:ljoshak
ID: 35450858
Thank you sir! Now the code is working (perfectly?), well, it is working and I can return it to the professor to check out. This was university project for C course and I can tell you that everyone is having hard times with this one. :) You've earned your status in this forum in my opinion.

Yours,

ljoshak
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35450889
Thank you for the kind words :)

I am glad to have been able to assist you in this, and will remain available for further questions you might have about this.
0
 

Author Comment

by:ljoshak
ID: 35450907
Wow, should've accepted many of your posts, but I think if someone checks this out he/she can see your amazing and helpful posts.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question