Jin Jin - 3 months ago 8
C Question

What's wrong with this code which saves every third character of a .txt file?

I'm trying to write a program which saves every third character of a .txt file. The text file's name used here is "Hello.txt" and it looks like this:

ABCDEFGHIJKLMNOPQRSTUVWXYZ


Below is the code which I have tried:

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

int main(int argc, char ** argv)
{
int ch;
int count = 0;
char name[20];
FILE *fp, *out;

fp = fopen(argv[1], "r"); // argv[1] is "Hello.txt"

strncpy(name, argv[1], 5); // Just copying "Hello"
name[5] = '\0';
strcat(name, "red"); // Adding "red" to "Hello"

out = fopen(name, "w"); // File pointer to "Hellored"

while( ( ch=getc(fp) ) != EOF) // Copying content of file "Hello.txt"
if (count % 3 == 0) // Only want to save every third character of "Hello.txt"
{
putc(ch, out);
count++;
}

}


As expected, it saves "Hellored" file in the workspace. But when I open it with adding ".txt" at the end of the file, the output is "A". What's wrong with this code?

Answer

You are not incrementing count properly. It needs to be incremented for every character not just inside the if block.

while( ( ch=getc(fp) ) != EOF)  // Copying content of file "Hello.txt"
{
   if (count % 3 == 0)         // Only want to save every third character of "Hello.txt"
   {
      fputc(ch, out);
   }

   // Increment count for every character.
   count++;
}

Additional cleanup:

Add code to close the files before the end of the function.

fclose(out);
fclose(fp);
Comments