Thread: Problem with swapping structures inside file

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    4

    Problem with swapping structures inside file

    Hi,i tried normal swapping method like this (counter is number of structures written in file) :
    Code:
    fopen("books.txt","r+");
    system ("cls");                  
    for(i=1;i<counter-1;i++){
    for(j=1+1;j<counter;j++){                           
    fscanf(f," %[^,], %[^,], %[^,], %[^,],%d",k[i].name,k[i].author,k[i].publisher,k[i].ISBN,&k[i].year);                                                                      
      if(strcmp(k[i].name,k[j].name)>0)
       {
                                                                                      
    t=k[i];
    k[i]=k[j];
    k[j]=t;
    fprintf(f,"%s,%s,%s,%s,%d\n",k[i].name,k[i].author,k[i].publisher,k[i].ISBN,k[i].year);}}
    }}}
    But it doesn't do anything. Help me pls

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    Perhaps you should read the whole file first, before trying to compare with struct elements which don't exist yet.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    505
    The inner loop should go j = 0 to i-1.
    But as a general approach, you need to put in diagnostic printfs to see what the program is doing.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 04-04-2012, 01:19 PM
  2. Declaring structures inside structures ?
    By jamaican1231 in forum C Programming
    Replies: 6
    Last Post: 04-13-2010, 03:40 PM
  3. Arrays of pointers inside structures.
    By Posto2012 in forum C Programming
    Replies: 7
    Last Post: 11-18-2009, 12:58 AM
  4. Accessing Structures Inside Structures
    By Mellowz in forum C Programming
    Replies: 1
    Last Post: 01-13-2008, 03:55 AM
  5. Replies: 3
    Last Post: 11-14-2005, 08:03 AM