• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 392
  • Last Modified:

example on reading a file like a string

I need an example of opening a file in C
and printing the contents of the file. I need to
be able to print certain sections of the file
0
pesst
Asked:
pesst
  • 3
  • 2
1 Solution
 
arnondCommented:
to dump the whole file do something like this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  FILE *inFile;
  char ch;

  inFile=fopen("test.txt");
  if (inFile==NULL)
  {
      printf ("error opening file.\n");
      exit(0);
  }
  while ( (ch=fgetc(inFile)) != EOF)
  {
      fputc(stdout);
  }

  return (0);
}


if you need to ouput sections, you need some more complex mechanisms to identify the begining and ending of the sections.

Will be glad to furthur assist.
Arnon David.
0
 
pesstAuthor Commented:
That is exactly what I wanted, what i want to do is print out 8 characters at a time and ignore any spaces inbetween the characters. can you suggest a way to do that.  you can go ahead and answer the question and I will award you the points
0
 
arnondCommented:
to print out 8 char at a time, use an 8 char array (char array[9]) and in the while loop do:

while ( (ch=fgetc(inFile)) != EOF)
{
  for (i=0;i<=7;i++)
  {
     if (ch==' ')
       continue; /* ignore spaces */
     array[i]=ch;   /*this fills the array with 8 non-space chars*/
  }
  array[9]='\0'; /* terminating NULL */
  printf ("%s",array); /* print out the 8 chars array - add '\n' if you want a new line in every iteration.*/
}

you can add more chars to ignore in the if statement like this:
if ( (ch==' ') || (ch='1') || (ch=='Z')) ......   will ignore spaces, 1's and capital z's.

Arnon David.
0
 
pesstAuthor Commented:
david,

your code doesn't do exactly what it is supposed to.
say I input the string 1 0 1 0 0 1 0 0.
it outputs:
111111111111111100000000000000001111111111111111
and so on just printing each character 16 times.
can you see what the problem is?
0
 
pesstAuthor Commented:
I fixed it. never mind
0

Featured Post

Easily manage email signatures in Office 365

Managing email signatures in Office 365 can be a challenging task if you don't have the right tool. CodeTwo Email Signatures for Office 365 will help you implement a unified email signature look, no matter what email client is used by users. Test it for free!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now