Thread: Reading a file

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    8

    Question Reading a file

    I'm new to C programming, and I'm trying to figure out a simple way to read the entire contents of a text file. Is there a way? I have a SQL file that has a lot of SQL code in it that I want to send to MySQL from my C program, but I don't know how to read the entire file.

    I guess I read it into a char[] array, but how? I've been looking it up on Google and I even have a book on programming in C, but I'm still confused.


    Thanks ahead of time,
    Alex.

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    You wouldn't want to read the entire file at once, just read a chunk and send it on its way.

    Have you looked at, fopen()/fgets()/fread() ?

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    8
    I've seen those. Why wouldn't I want to read the entire file at once?

    If I just take the file in chunks, then I have to make up some way to make sure that I have a full block of SQL code.

  4. #4
    Registered User
    Join Date
    Feb 2010
    Posts
    7
    Hi,

    Try out this piece of code. It should work for you.

    Code:
    char buf[1000];
    FILE *fp;
    
    fp = fopen("myfile.txt","r");
    
    if(fp == NULL)
    {
       printf("ERROR: Cannot open file\n");   
    }
    else
    {      
       while(!feof(fp))
       {
               buf = fgetc(fp);
       }
       fclose(fp);
    }

  5. #5
    Registered User
    Join Date
    Apr 2009
    Posts
    66
    I hope that sunny code would throw an error , it can be modified as *(buf+incremental_variable)=fgets(fp)
    to hold a character

    the following code used to take a whole lot of contents if we know the size of the file ,
    Code:
    buf=(char *)malloc(SIZE_OF_FILE);
     fread(buf,SIZE_OF_FILE,1,fp);
     printf("buffer: %s\n" ,buf);

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