-5

Say I have a file like so:

1234
56e8
1245

Is there a way I could read one character at a time and perform operations on them? Or, is there a way I can read a line and extract each character from it?

I've been trying to use strtok and use delimiter but can't seem to find a delimiter that can do the job.

admdrew
  • 3,790
  • 4
  • 27
  • 39
prod1
  • 11
  • 1
  • 2
  • So you want a `f`ile-`get`-`s`tring function, if only such a thing existed, and was called something rather intuitive like `fgets`. Before you learn to program, learn to use google, please – Elias Van Ootegem Oct 20 '14 at 15:03
  • 1
    possible duplicate of ["while( !feof( file ) )" is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – Elias Van Ootegem Oct 20 '14 at 15:03

2 Answers2

1

Yes, it is possible. An easy way to read cha racter by character would be to use fgetc:

int c;
FILE *fp = fopen("filename.txt", "r");

if (fp == NULL)
{
   printf("Error opening file!\n");
   return -1;
}

while ((c = fgetc(fp)) != EOF)
{
  // Character is read in `c`
  // Do something with it
}

fclose(fp);

As for reading line by line, use fgets:

char line[100];
FILE *fp = fopen("filename.txt", "r");

if (fp == NULL)
{
  printf("Error opening file!\n");
  return -1;
}

while (fgets(line, 100, fp) != NULL) /* Reads a line */
{
  // One line is stored in `line`
  // Do something with it
}

fclose(fp);
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

No need to use strtok if you want to examine every char.

There are many tutorials on this. This code will read one character at a time.

FILE * pFile;
int c;
pFile=fopen ("myfile.txt","r");
if (pFile==NULL) 
    perror ("Error opening file");
else
{
    do {
       c = fgetc (pFile);
    } while (c != EOF);
}
fclose (pFile);
igon
  • 3,016
  • 1
  • 22
  • 37