Thread: Help with some reading file

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    17

    Question Help with some reading file

    Hello.

    I have the following code to read one file.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    main()
    {
        char tam[2]={ };
        FILE *fp1, *fp2;
        char line[4];
        fp1 = fopen("brd2.ltr","r");
        fgets(tam,2,fp1);
        printf("TAMANHO->%s\n",tam);
        while(fgets(line,3,fp1))
       { 
       printf("%c%c%c",line[0],line[1],line[2]);
    
    
       } 
        fclose(fp1);
    }
    The file look like this:
    4
    A (B) A B
    (C)[B](A) D
    D (A) C D
    (A)[B](D) C

    I'm trying that my program does this:-
    First line : Size of board
    Next lines reading 3 by 3 chars and put then in 2D arrays.
    Now i have problems reading first line.

    tks in advanced,
    HIT

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Use larger arrays for your inputs.

    The first line at least needs to hold
    "4\n\0"
    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.

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    17
    If i replace

    Code:
    char tam[10]={ };
    fgets(tam,5,fp1);
    i got this output:

    Size-> A (
    B) A B
    (C)[B](A) D
    D (A) C D
    (A)[B](D) C

    Instead of
    Size->4
    A (B) A B
    ....
    ....

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Try

    char buff[BUFSIZ];

    and
    fgets( buff, sizeof buff, fp1 );
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM