#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    1
    Rep Power
    0

    Unhappy C Program Help Reading in a file of Chars until EOF


    Hi, I'm working on a project, and it requires me to read in a file of chars. I've been in java programming mode for a while, so forgive me for my C questions...it's been a while...

    Anyways, I have the first part written, where I'm just trying to read in my data.txt file, and I thought I had it written well. It compiles, but then it seg faults, and I'm not sure why. I used calloc for the array, but maybe I misused it? Or is it in my EOF statement? I'm still not sure if that's coded correctly. Below is my code. Any help would be appreciated!


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(int argc, char* argv[] )
    
    {
    /* Local Declarations*/
    int i;
    int *ptr;
    char tempc;
    
    /*Allocate enough space to hold each char*/
    int BigArray[26] = {0};
    	if(!(ptr=(int*)calloc (26, sizeof(char))))
    	exit(100);
    
    /* Open the file to read*/
    	FILE *f = fopen(argv[1], "r");
    
    /*Fill the Array with data from the file*/
    	while(1 == 1)
    	{
    		fscanf(f, "%c", &tempc);
    		if(tempc == EOF)
    		break;
    		
    		for(i = 0; i < 26; i++)
    			{
    			if(BigArray[i] == tempc)
    			{
    			break;
    			}
    		else if(BigArray[i] == 0)
    			{
    			BigArray[i] == tempc;
    			break;
    			}
    		else
    		;
    		} /*End for to check if in the array */
    	} /* End while to load the array */
    
    /*Print statement to check the array was filled correctly*/
    for(i = 0; i < 26; i++)
    {printf("%c", BigArray[i]);}
    	
    return 0;
    } /*End main*/
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,364
    Rep Power
    1870
    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

IMN logo majestic logo threadwatch logo seochat tools logo