Problem with swapping structures inside file

This is a discussion on Problem with swapping structures inside file within the C Programming forums, part of the General Programming Boards category; Hi,i tried normal swapping method like this (counter is number of structures written in file) : Code: fopen("books.txt","r+"); system ("cls"); ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,484
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    333
    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.
    http://www.malcolmmclean.site11.com/www

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-17-2009, 11:58 PM
  4. Accessing Structures Inside Structures
    By Mellowz in forum C Programming
    Replies: 1
    Last Post: 01-13-2008, 02:55 AM
  5. Replies: 3
    Last Post: 11-14-2005, 07:03 AM

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