Results 1 to 3 of 3

Thread: Put 25 characters from a file into a char array

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2002
    Posts
    4

    Put 25 characters from a file into a char array

    Greets all,

    I am messing around with files in C. I'll try to explain fully so you are able to help/understand me better. I'm trying to get a c program to open up a text file(with text in it already), and put the first 25 or so characters into a variable as i want to compare a defined string to the string of 25 characters from the file.

    Would anybody lend me a hand?

    Thanks.

  2. #2
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    Code:
    #include <stdio.h>
    #include <stdio.h>
    #include <stdlib.h>
    void test(FILE*);
    
    int main(){
            const char *compare= "this is 25 charaCTERS    ";
    	FILE *in;
    	char tmp[512];
    	test(in=fopen("myfile.txt","r"));
            while(!feof(in) ){
                    memset(tmp,0x00,sizeof(tmp));
    		if(fgets(tmp,511,in)!=NULL){
            	   tmp[25]=0x00;  /* tmp is now 25 characters long */
            	   if(!strncmp(tmp,compare,25)){
            	          printf("Equal\n");
    		   }else{
    			  printf("Not equal \n");
    		   }
            	}
            }
            fclose(in);
    	return 0;
    }
    
    void test(FILE *tst){
            if(tst==NULL){
    	       perror("Error on input file");
                   exit(EXIT_FAILURE);
                  }
    }

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Explain to me why you get 512 bytes when you want only 25? Because of the page size, the sector size? What optimization is that?
    On windows you should explicitly state whether to open the file in text or binary format.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width