Thread: Trouble reading file with dynamic allocation, can someone help?

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    8

    Trouble reading file with dynamic allocation, can someone help?

    hi everyone im doing a program the converts roman numbers into numerical numbers and i´m trying to read from a file some roman numbers and then converts then and show them on the console heres the part of the program where the problem resides:

    Code:
    void main() {
          if (f != NULL) {
                            
           NRomano1 = (char**) malloc (51 * sizeof(char*));
           Arabe1 = (int*) malloc (51 * sizeof(int));
    
    
            while (!feof(f)) {        
                for (i=0; i<51; i++) 
                    NRomano1[i] = (char*) malloc(51 * sizeof(char));
                for (i=0; i<51; i++) {
                    fgets(NRomano1[i], 51, f);
                     Arabe1[i] = teclado(NRomano1[i]); /*teclado is the function the converts the numbers*/
                                
                 }
                        
                 }
                for (i=0; i<51; i++) {
                      printf("O numero romano %s = %d em arabe\n", NRomano1[i], Arabe1[i]);
                }
            fclose(f);
    }
    its doesnt show debug errors its starts fine, and now the program will allocat 51 spaces i dont want to do that, i wanted that the program asks me how many numbers i want to convert and then goes to the file and reads the exact number i told him to but i cant get it right i´ve been trying to solve this for a long time the problem happens after openning the file, can somehelp me?

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    void main() {
          if (f != NULL) {
    Where do you declare "f"? Is it global?
    And it is "int main(void)".

    Code:
                           
           NRomano1 = (char**) malloc (51 * sizeof(char*));
           Arabe1 = (int*) malloc (51 * sizeof(int));
    Don't cast the return value of malloc!

    Code:
            while (!feof(f)) {
    That's not how feof is supposed to be used!

    Code:
    }
            fclose(f);
    }
    If you would use better indentation or turn on compiler warnings you would have realized that you are missing a closing brace.

    its doesnt show debug errors its starts fine, and now the program will allocat 51 spaces i dont want to do that, i wanted that the program asks me how many numbers i want to convert and then goes to the file and reads the exact number i told him to
    So you have problems with getting input from the user?
    Then just replace all your 51's with the number from the user.

    Bye, Andreas

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    SourceForge.net: cpwiki
    Read this for
    - void main
    - using feof()
    - indentation

    A couple of examples.
    1. To read the whole file, one line at a time
    Code:
    char buff[BUFSIZ];
    while ( fgets( buff, BUFSIZ, f ) != NULL ) {
        // do stuff with buff
    }
    2. To read the whole file, one line at a time, upto some number of lines
    Code:
    char buff[BUFSIZ];
    int numLine = 0, maxLine = 100; // or whatever
    while ( numLine < maxLine && fgets( buff, BUFSIZ, f ) != NULL ) {
        // do stuff with buff
        numLine++;
    }
    Oh, and in a C program, you shouldn't be casting the result of malloc
    FAQ > Casting malloc - Cprogramming.com
    Are you compiling it with a C++ compiler perhaps?

    Edit:
    Beaten to it again!
    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.

  4. #4
    Registered User
    Join Date
    Jun 2012
    Posts
    8
    Quote Originally Posted by AndiPersti View Post
    Code:
    void main() {
          if (f != NULL) {
    Where do you declare "f"? Is it global?
    And it is "int main(void)".

    Code:
                           
           NRomano1 = (char**) malloc (51 * sizeof(char*));
           Arabe1 = (int*) malloc (51 * sizeof(int));
    Don't cast the return value of malloc!

    Code:
            while (!feof(f)) {
    That's not how feof is supposed to be used!

    Code:
    }
            fclose(f);
    }
    If you would use better indentation or turn on compiler warnings you would have realized that you are missing a closing brace.



    So you have problems with getting input from the user?
    Then just replace all your 51's with the number from the user.

    Bye, Andreas
    yes the variables are global, i have the file f created just couldnt send all of the code because off the limit of the tags or just dont know how add tags right, and yes i replaced 51 with the a variable the gets a nuber input by the user and in the end it doesnt show anything

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Trouble reading file with dynamic allocation, can someone help? - Dev Shed
    Just in case people repeat what has already been said elsewhere.

    Here's another clue
    choose yo' forum doodz
    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.

  6. #6
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    From the other forum:
    Code:
    char drive[10], ficheiro[20]
    gets(drive);
    strcat(drive,":\\");
    gets(ficheiro);
    strcat(drive, ficheiro);
    f= fopen(drive, "r");
    Basic maths: How long can the filename (ficheiro) be, if it should fit inside a 10 char array, when you have already used at least 5 characters (drive letter + ":\\" + "\0")?
    In this situation it just adds to the problem that you declare ficheiro as a 20 char array and use gets. (And please do yourself a favor and read about fflush).

    Where do you learn all this crap?

    Bye, Andreas

  7. #7
    Registered User
    Join Date
    Jun 2012
    Posts
    8
    Quote Originally Posted by AndiPersti View Post
    From the other forum:

    Basic maths: How long can the filename (ficheiro) be, if it should fit inside a 10 char array, when you have already used at least 5 characters (drive letter + ":\\" + "\0")?
    In this situation it just adds to the problem that you declare ficheiro as a 20 char array and use gets. (And please do yourself a favor and read about fflush).
    but, how does that solve the problem what your saying if im understanding correctly is it shouldnt be as 20 char array (ficheiro) but i have that much space in case i need to input a bigger string, i dont think it interfere's with nothing it just fills the space required.

    the code just opens the file and its working fine the problem is when i try to read the file using dynamic allocation, you had some hint i could follow im still learning.

  8. #8
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Show your complete program.

  9. #9
    Registered User
    Join Date
    Jun 2012
    Posts
    8
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    	
    
    
    	
    int teclado(char NRomano[]){ /*function that converts the numbers*/
    	int tam = strlen(NRomano);
    	int	arabe = 0;
    	for (int i=0; i<tam; i++) {
    		switch (NRomano[i]) {
    			case 'V': arabe = arabe + 5;
    				break;
    			case 'L': arabe = arabe + 50;
    				break;
    			case 'D': arabe = arabe + 500;
    				break;
    			case 'M': arabe = arabe + 1000;
    				break;
    			case 'I': 
    				if (i == tam-1) 
    					arabe = arabe + 1;
    				else if (NRomano[i+1] != 'I') 
    					arabe = arabe - 1;
    				else 	
    					arabe = arabe + 1;
    				break;
    			case 'X':
    				if (i == tam-1 ) 
    					arabe = arabe + 10;
    					else if (( NRomano[i+1] != 'I') && (NRomano[i+1] != 'V') && (NRomano[i+1] != 'X')) 
    						arabe = arabe - 10;
    					else 
    						arabe = arabe + 10;
    				break;
    			case 'C': 
    				if (i == tam-1) 
    					arabe = arabe + 100;
    					else if (( NRomano[i+1] != 'M') && ( NRomano[i+1] != 'D')) 
    						arabe = arabe + 100;
    					else 
    						arabe = arabe - 100;
    					break;
    			}
    	}
    	return arabe;
    }
    
    
    void main() {
    
    
    	char escolha, op;
    
    
    	do{
    		system("cls");
    		printf("Conversao de numeros romanos para arabe !!\t");
    		printf("\n\n");
    		printf("Como quer fornecer os dados?\n\n");
    		printf("---------------------------------------\n");
    		printf("|                                     |\n");
    		printf("|    Por Ficheiro                 [1] |\n");
    		printf("|    Por Teclado                  [2] |\n");
    		printf("|    Deseja Sair do Programa ?    [3] |\n");
    		printf("|                                     |\n");
    		printf("---------------------------------------\n\n");
    		printf("Qual e a sua escolha?: ");
    		fflush(stdin);
    		scanf("%c", &escolha);
    
    
    		switch(escolha){
    			case '1': 
    				FILE *f;
    				int  ne1, *Arabe1, i;
    				char **NRomano1;
    				char drive[10], ficheiro[10];
    				
    					system("cls");
    					printf("Qual a drive?\n");
    					fflush(stdin);
    					gets(drive);
    					strcat(drive,":\\");
    					printf("Qual o nome do ficheiro?\n");
    					fflush(stdin);
    					gets(ficheiro);
    					strcat(drive, ficheiro);
    					f= fopen(drive, "r");
    					printf("\n\n");
    					
    					printf("Quantos numeros romanos quer converter?: ");
    					scanf("%d", &ne1);
    					if (f != NULL) {
    						
    							NRomano1 = (char**) malloc (ne1 * sizeof(char*));
    							Arabe1 = (int*) malloc (ne1 * sizeof(int));
    
    
    						while (!feof(f)) {		
    
    
    							for (i=0; i<ne1; i++) 
    								NRomano1[i] = (char*) malloc(ne1 * sizeof(char));
    
    
    						
    							for (i=0; i<ne1; i++) {
    
    
    								fgets(NRomano1[i], ne1, f);
    								Arabe1[i] = teclado(NRomano1[i]);
    							
    							}
    					
    						}
    						for (i=0; i<ne1; i++) {
    							printf("O numero romano %s = %d em arabe\n", NRomano1[i], Arabe1[i]);
    						}
    
    
    					}
    					else {
    						puts("Nao e possivel abrir o ficheiro");
    					}
    							
    					fclose(f);
    			break;
    
    
    			case '2':
    					FILE *fp;
    					int k, *Arabe, ne;
    					char **NRomano;
    	
    
    
    						system("cls");		
    						fp = fopen("C:\\exe\\romano.txt","w");
    			
    						printf("Quantos numeros romanos quer converter?: ");
    						scanf("%d", &ne);
    						
    						NRomano = (char**) malloc (ne * sizeof(char*));
    						Arabe = (int*) malloc (ne * sizeof(int));
    						printf("\n\n");
    
    
    						for (k=0; k<ne; k++) 
    							NRomano[k] = (char*) malloc(ne * sizeof(char));
    
    
    						for (k=0; k<ne; k++) {
    							printf("Digite o numero romano: "); 
    							fflush(stdin);
    							gets(NRomano[k]);	
    							Arabe[k] = teclado(NRomano[k]);
    							
    						}
    						printf("\n\n");
    						for (k=0; k<ne; k++){
    							printf("O numero romano %s = %d em arabe\n", NRomano[k], Arabe[k]);		
    							fprintf(fp,"O numero romano %s = %d em arabe\n", NRomano[k], Arabe[k]);
    						}
    						
    						fclose(fp);
    					
    				break;
    			case '3': exit(1);
    				break;
    		}
    		printf("\n");
    		printf("Deseja Sair?\n");
    		fflush(stdin);
    		scanf("%c", &op);
    	}while( op == 'n');
    }
    here it is, the part of the problem is in the switch case "1", when i run the program it asks me wich drive i want and the name of the file to read it(the file has 2 roman number) and then i ask the program how many numbers i want to convert i choose "1" and the program stops there and doesnt show anything. and i dont know if its useful but i use visual studio.

  10. #10
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Debugging 101:

    Code:
    strcat(drive, ficheiro);
    printf("drive = %s\n", drive);  // insert this line and tell us what it shows
    f= fopen(drive, "r");

  11. #11
    Registered User
    Join Date
    Jun 2012
    Posts
    8
    Quote Originally Posted by AndiPersti View Post
    Debugging 101:

    Code:
    strcat(drive, ficheiro);
    printf("drive = %s\n", drive);  // insert this line and tell us what it shows
    f= fopen(drive, "r");
    it show's this:

    drive = D:\exemplo.txt

    wich means its going to the file correctly, right?

  12. #12
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    That shows that you're far out in the land of undefined behaviour because you've declared drive as a 10 char array but it uses 15 ('\0' included). In other words you have a buffer overrun.

    Let's continue:
    Code:
    f= fopen(drive, "r");
    printf("\n\n");
    printf("Quantos numeros romanos quer converter?: ");
    scanf("%d", &ne1);
    printf("f = %p\n", f);        // another new line
    printf("ne1 = %d\n", ne1);    // and another
    if (f != NULL) 
    {
    
        printf("Inside if\n");    // do you see a pattern?
    
        NRomano1 = (char**) malloc (ne1 * sizeof(char*));
    
        Arabe1 = (int*) malloc (ne1 * sizeof(int));
    This is the basic way to debug a program. Put in printf's in strategic places and look at the output (or how far you can get before the program crashes).

    Bye, Andreas

  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You have already received a bunch of advice that you have clearly not acted on.

    If you are not going to act on advice you receive, why would you expect people to keep trying to help you? This is not a free debugging service. You actually have to show some effort.

    Also, your code repeatedly does fflush(stdin). fflush() gives undefined behaviour on input streams. So it is a really BAD idea to do that.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  14. #14
    Registered User
    Join Date
    Jun 2012
    Posts
    8
    hmm, ok i noted that i'll try see if i can solve this, but still i think its missing something that it makes it not read, but i dont know what.

  15. #15
    Registered User
    Join Date
    Jun 2012
    Posts
    8
    Quote Originally Posted by grumpy View Post
    You have already received a bunch of advice that you have clearly not acted on.

    If you are not going to act on advice you receive, why would you expect people to keep trying to help you? This is not a free debugging service. You actually have to show some effort.

    Also, your code repeatedly does fflush(stdin). fflush() gives undefined behaviour on input streams. So it is a really BAD idea to do that.
    i know and thank you for the advise im not dissing anyome or mistreating i just like to understanding what i dont get, and i asks just a lot of questions xD

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 06-04-2008, 10:39 PM
  2. Trouble reading from file
    By neolyn in forum C++ Programming
    Replies: 5
    Last Post: 12-11-2004, 02:48 PM
  3. Help with file reading/dynamic memory allocation
    By Quasar in forum C++ Programming
    Replies: 4
    Last Post: 05-17-2004, 03:36 PM
  4. Dynamic memory allocation for file handling
    By prashanth_sh in forum C Programming
    Replies: 2
    Last Post: 11-07-2002, 05:50 AM
  5. Reading in from 1 file into 1 dynamic structure
    By ajax in forum C Programming
    Replies: 2
    Last Post: 07-22-2002, 02:40 AM