fread

This is a discussion on fread within the C Programming forums, part of the General Programming Boards category; i'm inputting a file that has a sample of text with multiple lines. i'm using fread to read it into ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    16

    fread

    i'm inputting a file that has a sample of text with multiple lines. i'm using fread to read it into a 1D array that has a max of 5000 characters. The text file will have less than 5000 characters but for some reason when i read in the file, it repeats the last two lines of the text file into the array, does anyone have any idea why this would be happening?

    Dyn4sty22

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Without seeing the code, it would be very difficult to predict what you are doing wrong.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,424
    it repeats the last two lines of the text file into the array
    using feof to control the read loop?
    check the FAQ and do not do it.
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  4. #4
    Registered User
    Join Date
    Mar 2008
    Posts
    16
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    /*Include this so we can calculate the runtime*/
    #include <time.h>
    
    
    /*Declare necessary constants*/
    #define LENGTH 80
    #define MAX 5000
    #define ALPHABET 27
    
    int encrypt()
    {
    	/*Declare necessary variable and arrays for inputs/string manipulations etc.*/
    	char keyName[LENGTH] = {0};
    	char clearTextName[LENGTH] = {0};
    	char storeFileName[LENGTH] = {0};
    	char clearText[MAX]={0};
    	char key[ALPHABET]={0};
    	int z=0, x=0;
    	FILE* input;
    
    	/*Declare variables for the clock*/
    	clock_t start, end;
    	double runTime;
    
    	/*******************************************************************
    	  Asks the user for the three required files: key, cleartext and 
    	  storage file names
                   *******************************************************************/
    	printf("Enter the key file name and its extension(.txt): ");
    	scanf("&#37;s",&keyName);
      
    	printf("Enter the cleartext file name and its extension(.txt): " );
    	scanf("%s",&clearTextName);
    
    	printf("Enter the store file name and its extension(.txt): ");
    	scanf("%s",&storeFileName);
    
    	/*Start clock*/
    	start = clock();
    
    	/********************************************************************
    	 Reads in the key and stores it
    	********************************************************************/
    	/*Returns null if file could not be found*/
    	input = fopen(keyName, "r");
    	if (input==NULL)
    	{
    		printf("could not open file to read\n");
    		return 0;
    	}
    
    	/*Stores the key in the array key*/
    	fgets(key, ALPHABET, input);
    	fclose(input);
    	/********************************************************************
    	 Reads in the clear text and stores it
    	********************************************************************/
    	/*Returns null if the cleartext file couldnt be found*/
    	input = fopen(clearTextName, "r");
    	if (input==NULL)
    	{
    		printf("could not open file to read\n");
    		return 0;
    	}
    
    	/*Stores the strings found in cleartext into the aray clearText*/
    	fread(clearText, sizeof(char), MAX, input);	
                    fclose(input);
    	/*******************************************************************
    	 Encrypt the message
    	*******************************************************************/
    	/*Creates a loop that runs through the whole array and switches
    	  out the characters with the characters specified in the 
    	  array key*/
    		
    	for(x=0;x<strlen(clearText);x++)
    		{
    			if(isupper(clearText[x]))
    			{
    						
    				z=clearText[x]-65;
    				clearText[x]=key[z];
    				clearText[x]=clearText[x]-32;
    			}
    			else if(islower(clearText[x]))
    			{
    				z=clearText[x]-97;
    				clearText[x]=key[z];
    			}
    			else
    				clearText[x]=clearText[x];
    		}
    		
    	/********************************************************************
    	 Stores array in designated file
    	********************************************************************/
    	/*Returns null if the store file couldnt be found (not necessary
    	  because the file is created if the file cant be found) */
    	
                    input = fopen(storeFileName, "w+");
    	if (input==NULL)
    	{
    		printf("could not open file to read\n");
    		return 0;
    	}
    
    	/*Runs through array and stores the data in the specified file */
    	fputs(clearText,input);
    	fclose(input);
    
    	/*Stops the clock and calculates the run time and outputs it's value */
    	end = clock();
    	runTime = ((end - start) / (double) CLOCKS_PER_SEC );
    	printf("The run time of this encrypt function is %g seconds", runTime);
    	return 0;
    }

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Code:
    fread(clearText, sizeof(char), MAX, input);	
    /* ... */
    for(x=0;x<strlen(clearText);x++)
    Rather than discarding the return value of fread (the number of items read) use it as the control for the loop.

    Avoid using strlen as the loop control anyway.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    Registered User
    Join Date
    Mar 2008
    Posts
    16
    it store it like this in the output file

    Kubla Khan or, a Vision In a Dream: A Fragment

    In Xanadu did Kubla Khan
    A stately pleasure dome decree:
    Where Alph, the sacred river, ran
    Through caverns measureless to man
    Down to a sunless sea.
    So twice five miles of fertile ground
    With walls and towers were girdled round:
    And there were gardens bright with sinuous rills,
    Where blossomed many an incense-bearing tree;
    And here were forests ancient as the hills,
    Enfolding sunny spots of greenery.

    But oh! that deep romantic chasm which slanted
    Down the green hill athwart a cedarn cover!
    A savage place! as holy and enchanted
    As e'er beneath a waning moon was haunted
    By woman wailing for her demon lover!
    And from this chasm, with ceaseless turmoil seething,
    As if this earth in fast thick pants were breathing,
    A mighty fountain momently was forced:
    Amid whose swift half-intermitted burst
    Huge fragments vaulted like rebounding hail,
    Or chaffy grain beneath the thresher's flail:
    And 'mid these dancing rocks at once and ever
    It flung up momently the sacred river.
    Five miles meandering with a mazy motion
    Through wood and dale the sacred river ran,
    Then reached the caverns measureless to man,
    And sank in tumult to a lifeless ocean:
    And 'mid this tumult Kubla heard from far
    Ancestral voices prophesying war!

    The shadow of the dome of pleasure
    Floated midway on the waves;
    Where was heard the mingled measure
    From the fountain and the caves.
    It was a miracle of rare device,
    A sunny pleasure-dome with caves of ice!

    A damsel with a dulcimer
    In a vision once I saw:
    It was an Abyssinian maid,
    And on her dulcimer she played,
    Singing of Mount Abora.
    Could I revive within me
    Her symphony and song,
    To such a deep delight 'twould win me,
    That with music loud and long,
    I would build that dome in air,
    That sunny dome! those caves of ice!
    And all who heard should see them there,
    And all should cry, Beware! Beware!
    His flashing eyes, his floating hair!
    Weave a circle round him thrice,
    And close your eyes with holy dread,
    For he on honey-dew hath fed,
    And drunk the milk of Paradise.

    -- Samuel Taylor Coleridge (1772-1834)
    milk of Paradise. /*shouldnt be here*/

    -- Samuel Taylor Coleridge (1772-1834) /*shouldnt be here*/

  7. #7
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    I forgot to add -- open the files in binary mode.

    [edit]Regarding the loop, try
    Code:
    size_t len;
    /* ... */
    len = fread(clearText, MAX, sizeof *clearText, input); /* note swapped order */
    /* ... */
    for(x=0;x<len;x++)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #8
    Registered User
    Join Date
    Mar 2008
    Posts
    16
    should i still open it in binary mode? if not, i keep getting 0 for len

  9. #9
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Just out of curiosity, wouldn't it be better to use:
    Code:
    len = fread(clearText, sizeof *clearText, MAX, input);
    Or is there some way to determine how much was read using the swapped order?

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    I screwed up the ordering (I never remember the order of the middle two parameters, I should have looked it up).
    Code:
    len = fread(clearText, sizeof *clearText, MAX, input);
    /* ... */
    fwrite(clearText, sizeof *clearText, len, input); /* replaced your fputs, may not be the issue */
    This is, for me, producing an output file that is the same size as the input file.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    Registered User
    Join Date
    Mar 2008
    Posts
    16
    Perfect!! thanks Dave, you're a life saver!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fread problems or memory problems
    By Lechuza in forum C Programming
    Replies: 1
    Last Post: 03-22-2009, 12:45 PM
  2. Another link from Microsoft about bug in fread
    By vart in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 05-06-2008, 11:56 AM
  3. How to load pixels of BMP into an array
    By brconner in forum Windows Programming
    Replies: 10
    Last Post: 06-02-2007, 04:30 AM
  4. Why is fread sometimes taking so long?
    By manugarciac in forum C++ Programming
    Replies: 2
    Last Post: 04-28-2007, 11:25 PM
  5. fread item_size limit
    By nvoigt in forum C++ Programming
    Replies: 2
    Last Post: 03-30-2005, 08:08 AM

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