Hey

I have a file named filetext.txt with the text:

One word
Two words
Three words
Four words

and the program should read this filetext.txt and output to another file called filecopied.txt this text:

One
Two
Three
Four

I have this so far:

#include <assert.h>
#include <complex.h>
#include <ctype.h>
#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <inttypes.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>



int main()
{
    FILE *filetext
    FILE *filecopied;
    char text[50];

    filetext=fopen("filetext.txt","r");
    filecopied=fopen("filecopied.txt","w");

    if ((filetext==NULL) || (filecopied==NULL))
        {
            printf ("A file cannot be opened");
            return 1;
        }

       // fgets(text,50,filetext);
        //sscanf("%s ",text);
        sscanf("%s\n",fgets(text,50,filetext));
        //sscanf("%s\n",fgets(text,50,filetext));
        fprintf(filecopied,"%s",text);
        fclose(filecopied);
        fclose(filetext);
        return 0;
}

It doesnt write anything to the file so how can I solve it? Id like to use fgets, fprintf, and sscanf. Thanks.

Dani AI

Generated

Short diagnosis and a small checklist to get this working reliably.

Your code has three practical problems: a syntax error (the FILE *filetext line is missing a semicolon), the call order for sscanf is wrong, and you only attempt to handle a single read instead of looping until EOF. sscanf expects the input string first and the format second; calling sscanf with the arguments reversed leads to undefined behavior. Also always check the return values of fopen, fgets and sscanf so you can detect errors early.

Fixing steps (no full program shown here so it does not repeat existing posts):

  • Include just the headers you need (for example stdio.h, string.h, ctype.h) and fix the missing semicolon.
  • Open both files and test for NULL. Use "r" and "w" modes and perror or fprintf(stderr, ...) on failure.
  • Read each input line in a loop with fgets. For each non-NULL line, extract the first space-delimited token (or decide how to treat blank lines).
  • When using sscanf use a width limit based on your destination buffer (format template: use a width equal to buffer_size-1) and check that sscanf returns 1 before calling fprintf.
  • If you prefer not to use a second buffer, scan the fgets buffer for the first whitespace (use isspace) and write characters up to that point to the output file, then write a newline.

Notes and cautions:

  • %s in sscanf skips leading whitespace and stops at the first whitespace; that behavior is usually what you want here. Always include a width in the format to prevent overflow.
  • If input lines can be arbitrarily long, consider getline (POSIX) or a dynamic-buffer approach; otherwise pick a sensible static line buffer size and handle truncation.
  • Both and already showed the two usual, correct approaches (token-extraction with sscanf and manual scanning with isspace); either is fine once the above fixes are applied.

Recommended Answers

All 5 Replies

int main()
{
   FILE *filetext;
   FILE *filecopied;
   char text[50];

   filetext=fopen("filetext.txt","r");
   filecopied=fopen("filecopied.txt","w");

   if ( (filetext==NULL) || (filecopied==NULL) )
   {
      printf ("A file cannot be opened");
      return 1;
   }

   while ( fgets(text, sizeof text, filetext) )
   {
      char first[10];
      if ( sscanf(text, "%9s", first) == 1 )
      {
         fprintf(filecopied, "%s\n", first);
      }
   }
   fclose(filecopied);
   fclose(filetext);
   return 0;
}
#include <assert.h>
#include <complex.h>
#include <ctype.h>
#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <inttypes.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>

It is always good to learn which headers contain which declarations. Including everything under the sun when you use only a small fraction of it is rarely a good idea.

It doesnt write anything to the file so how can I solve it?

Double check the way sscanf() is supposed to be called. What you want are two strings, one for input and one for output:

char line[512];
char word[512];

while (fgets(line, sizeof line, filetext))
{
    if (sscanf(line, "%511s", word) == 1)
    {
        fprintf(filecopied, "%s\n", word);
    }
}

I think both of you just limit in another array the amount of chars in a char array when I want it to read/write the first letters then when it detects the first space (" ") and when it detects a "\0", it should just to the next line again the first space and again a "\0" until it reaches EOF...

Maybe I didnt understand someone correctly...

Id like to use fgets, fprintf, and sscanf.

I want it to read/write the first letters then when it detects the first space (" ") and when it detects a "\0", it should just to the next line again the first space and again a "\0" until it reaches EOF

These wants do not jive. If you use fgets() alone, you have no choice but to provide a buffer large enough to hold the maximum expected line length. If you use sscanf() to extract a word, you have no choice but to provide a buffer large enough to hold the maximum expected line length because the whole line could be one big word.

You can skip using sscanf() entirely by searching for the first whitespace in the line and save the memory for the second buffer:

char line[512];

while (fgets(line, sizeof line, filetext))
{
    size_t x = 0;

    while (line[x] && !isspace(line[x])) putc(line[x], filecopied);

    putc('\n', filecopied);
}

The algorithm from the second quote is a viable option, but I would need some convincing to believe that it is a better option than fgets() and sscanf(). Right now I am not sure what it is you want. Dave and I have both given you solutions that match your functional requirement of saving the first word in each line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.