bob9123
bob9123

Reputation: 755

Counting characters one by one from a textfile

My program requires to get input from a textfile and output it on a single line.

However if the amount of characters on a singular line exceed 60, there should be a new line.

The code I have so far:

 int main(int argc, char *argv[]){
 FILE *pFile;
 char x[10];
 char *token;
 pFile = fopen("test5.txt","r");
 int wordLength;
 int totalCharLength;
 char newline[10] = "newline";


 if(pFile != NULL){
        while (fgets(x, sizeof(x), pFile) != NULL) {
         token = strtok(x,"\r\n");
         if(token != NULL){
                printf("%s",x);

            }

         else{
                printf("%s",x);
        }
        //counter++;
        wordLength = strlen(x);
        totalCharLength += wordLength;
        printf("%d",totalCharLength);
        if(totalCharLength == 60){
            printf("%s",newline);
        }

    }

        fclose(pFile);
}
}

Textfile:

 a dog chased 

 a cat up the 

 tree. The cat 

 looked at the dog from 

 the top of the tree.  

There are 5 separate lines. Which displays this. This is not all on one line.

Output:

 a dog chased a cat up the tree. The cat looked at the dog from the top of the tree.

Now the program needs to be able to get input text in that format and print out in a single line.

So the above Output there should be a new line at the 60th char which is before second word "dog".

However I want to add a feature so that there is a counter for character and it prints a new line when character count = 60.

Now with some more debugging I added the code

 printf("%d",totalCharLength);

just before the if(totalCharLength==60) line and I realize that the characters get counted in random increments instead of one by one. Output:

 a dog cha9sed 13a cat up 22the 26tree. The35 cat 40looked at49 the dog 58 from 63 the top o72f the tre81e.  85

So this shows that it does not count character by character. However when I change charx[10] to a lower value it does not print everything on one line. It will leave gaps.

Example: Changing charx[10] to charx[2]

This correctly gets character by character however the output is not in on one line.

The only time there should be a new line is when characters exceed 60 in a line. Not 14 (First line).

 a2 3d4o5g6 7c8h9a10s11e12d13 14
 30a17 18c19a20t21 22u23p24 25t26h27e28 29
 46t32r33e34e35.36 37T38h39e40 41c42a43t44 45
 71l48o49o50k51e52d53 54a55t56 57t58h59e60newline 61d62o63g64 65f66r67o68m69   70
 72t73h74e75 76t77o78p79 80o81f82 83t84h85e86 87t88r89e90e91.92 93 94

Upvotes: 3

Views: 203

Answers (6)

BLUEPIXY
BLUEPIXY

Reputation: 40155

#include <stdio.h>
#include <ctype.h>

int main(void){//unused argv
    FILE *pFile;
    int ch, prev = 0;
    int totalCharLength = 0;
    int wrap_size = 60;
    //char newline[] = "newline";

    pFile = fopen("test5.txt","r");

    if(pFile != NULL){
        while((ch = fgetc(pFile)) != EOF){
            if(isspace(ch))
                ch = ' ';
            if(prev == ' ' && ch == ' ')
                continue;//unified
            prev = ch;
            putchar(ch);
            if(++totalCharLength == wrap_size -1){//-1 : include newline
                putchar('\n');//printf("%s", newline);
                totalCharLength = 0;
            }
        }
        fclose(pFile);//put inside if-block
    }

    return 0;
}

Upvotes: 0

Andrea Gilmozzi
Andrea Gilmozzi

Reputation: 63

I think you are best just printing each char on his own, and check for a space before adding the newline.

Something like:

((charCount > 60) && (currentChar == ' ')) {
    // print newline and reset counter
    printf("\n");
    charCount = 0;
}

Edit: before anything check if the current char is a newline already and skip it. Check the carriage return \r as well since in windows newlines are \r\n.

#include <stdio.h>

int main(void) {
  FILE *f = fopen("test.txt", "r");
  if(!f) {
    printf("File not found.\n");
    return 1;
  }

  char c;
  int cCount = 0;
  while((c = fgetc(f)) != EOF) {
    if(c == '\r') continue;
    if(c == '\n') c = ' ';

    printf("%c", c);
    if((cCount++ > 60) && (c == ' ')) {
      printf("\n");
      cCount = 0;
    }
  }

  fclose(f);
  return 0;
}

Upvotes: 1

user3386109
user3386109

Reputation: 34839

In the first case, when you had char x[10], fgets will read up to 9 characters, or until a newline is found. So the output is

a dog cha9sed 13a cat up 22the 26

because the first call to fgets reads 9 characters (and then prints 9), the second call reads up to the newline (prints 13), the third call reads nine characters (prints 22), and the fourth call reads up to the newline (prints 26).

When you change to char x[2], fgets will only read one character at a time. And this causes strtok to work differently than you expect. When a string contains only delimiter characters, strtok will return NULL and the string is unmodified. So if the string contains only a newline character, strtok won't remove the newline, like you expect.

To fix the code, use fgetc to read characters and don't use strtok at all.

int main( void )
{
    FILE *pFile;
    if ( (pFile = fopen("test5.txt","r")) == NULL )
        exit( 1 );

    int c, count;

    count = 0;
    while ( (c = fgetc(pFile)) != EOF ) {
        if ( c == '\n' )
            putchar( ' ' );
        else
            putchar( c );

        count++;
        if ( count == 60 ) {
            putchar( '\n' );
            count = 0;
        }
    }
    putchar( '\n' );
    fclose(pFile);
}

Here's the file that I tested with

a dog chased
a cat up the
tree. The cat
looked at the dog from
the top of the tree.

Upvotes: 0

Lukas
Lukas

Reputation: 3433

There you go

int main() {
    FILE *pFile = fopen("test.txt","r");
    int c, counter = 0;
    if (pFile != NULL) {
        while ((c = getc(pFile)) != EOF) {
            counter++;
            if (c != '\n') { putchar(c); }
            if (counter == 60) {
                counter = 0;
                printf("\n");
            }
        }
    }
    fclose(pFile);
}

Upvotes: 1

Mutex202
Mutex202

Reputation: 31

It goes like this,

#include<stdio.h>
//#pragma warning(disable : 4996)


int main()
{
    FILE *pfile;
    char data;
    int count = 1;
    pfile = fopen("test.txt", "r");
    printf("Opening file...\n");
    if (pfile == NULL)
    {
        printf("Error!\n");
    }

    while ((data = fgetc(pfile)) != EOF)
    {
       if (count != 60)
       {
          if (data != '\n')
          {
            printf("%c", data);
            count++;
          }

       }
       else
       {
          printf("\n");
          count = 1;
       }

    }
    fclose(pfile);
  return 0;
}

Upvotes: 0

scerrecrow
scerrecrow

Reputation: 269

if(token != NULL){
            printf("%s",x);
           strcat(newArray, x);
        }

After printing out the token, have a separate array that you concatenate the token too. This will give you the entire file on one line. It will be much easier from here to parse out the 60 characters then print lines as you go.

Upvotes: 0

Related Questions