tags:

views:

104

answers:

3

Hey guys...In C, I wish to read a file in my current working directory (nothing fancy), into a string. Later, I'd like to print that string out so I can do some work on it. I'm more used to Java, so I'm getting my chops on C and would love an explanation on how to do this! Thanks fellas...

+1  A: 

You might start with fopen and fread.

John Zwinck
Or he might use mmap()?
Jonathan Leffler
Sure, though the sequential and small nature of the file reading in this case makes it less likely I think.
John Zwinck
+2  A: 

You will use:

FILE *f = fopen(filename, "r");

To open the file. If that returns non-null, you can use:

char buf[MAXIMUM_LINE_SIZE];    /* pick something for MAXIMUM_LINE_SIZE... */
char *p;

while ((p=fgets(buf, sizeof(buf), f)))
{
   /* Do something with the line pointed to by p */
}

To do something more sophisticated (not bounded by an arbitrary size, or spanning multiple lines) you'll want to learn about dynamic memory allocation: the functions malloc(), realloc(), free()...

Some links to help you:

Also, just to throw it out there: If you are interested in writing C++ instead of C, that also has its own file I/O and string stuff that you may find helpful, and you won't have to do all the memory allocations yourself. But even then, it's probably good to understand the C way also.

asveikau
+3  A: 

Here's a C program that will read a file and print it as a string. The filename is passed as an argument to the program. Error checking would be a good thing to add.

int main(int argc, char *argv[])
{
  FILE    *f;
  char    *buffer;
  size_t  filesize;

  f = fopen(argv[1], "r");

  // quick & dirty filesize calculation
  fseek(f, 0, SEEK_END);
  filesize = ftell(f);      
  fseek(f, 0, SEEK_SET);

  // read file into a buffer
  buffer = malloc(filesize);
  fread(buffer, filesize, 1, f);

  printf("%s", buffer);

  // cleanup
  free(buffer);
  return 0;
}
Carl Norum
Really wonderful, thanks mate!
R.
Now that I look at it, I don't know off the top of my head if `buffer` is really going to be null terminated or not. Be careful out there!
Carl Norum
The buffer is definitely not guaranteed to be NUL-terminated. The other obvious (to me) bad thing that could happen is a NUL character in the file, but I'd say "nothing fancy" probably means that won't happen. And reader should note that adding error checking isn't simple - what you see here is less than half the size of the final error-proof code. fread's postconditions especially are quite subtle, it's allowed to part-complete.
Steve Jessop
+1, thanks @onebyone.
Carl Norum