0

What I want to do for now is have an input text file, load its content into a 2d array, perform something on it and then put it out into another file. Essential problem for me is keeping the original files' structure. This is my code:

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

int main(void)
 {
  FILE *ifp, *ofp;
  char buffer[100];
  int i, c;

  ifp=fopen("test.in", "r");
  ofp=fopen("test.out", "w");

  while (!feof(ifp)){
  if(fscanf(ifp, "%s", buffer) != 1)
   break;
  fprintf(ofp, "%s", buffer); 
}  
return 0;
}

my input:

aaa bb bbb
bbbbb bbbb aa

and output:

aaabbbbbbbbbbbbbbaa

Everything I tried for EOL or EOF recognition caused infinite loops. Performing anything with "%c" instead of "%s" resulted in worse outputs. Thanks in advance. edit: I'm aware I can get the output to be words with spaces between them or have every word in a new line but I don't know how to get from here to final result.

ijkl
  • 23
  • 3
  • 1
    Why not use `fgets`? That takes whole lines. You are reading words and then printing them to the file, which gets rid of whitespace. (`scanf` reads until whitespace, so words) – Arc676 Nov 26 '15 at 13:44
  • `getline()` could be very useful here if you need to preserve the structure of the file. – Samidamaru Nov 26 '15 at 14:00
  • OT: But still related: http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – alk Nov 26 '15 at 14:04
  • [while feof is always wrong](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – pmg Nov 26 '15 at 14:34

2 Answers2

0

Use "%c"

#include <stdio.h>

int main(void)
{
  FILE *ifp, *ofp;
  char buffer;

  ifp=fopen("test.in", "r");
  if(ifp==NULL)return 1;
  ofp=fopen("test.out", "w");
  if(ofp==NULL){
    fclose(ifp);
    return 1;
  }

  for(;;){
    if(fscanf(ifp, "%c", &buffer) != 1)
      break;
    fprintf(ofp, "%c", buffer); 
  }
  fclose(ifp);
  fclose(ofp);
  return 0;
}

or getc().

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

int main(void)
{
  FILE *ifp, *ofp;
  int buffer;

  ifp=fopen("test.in", "r");
  if(ifp==NULL)return 1;
  ofp=fopen("test.out", "w");
  if(ofp==NULL){
    fclose(ifp);
    return 1;
  }

  for(;;){
    if((buffer = getc(ifp)) != EOF)
      break;
    putc(buffer, ofp); 
  }
  fclose(ifp);
  fclose(ofp);
  return 0;
}

You won't neeed feof() because the functions used to read will detect EOF.

Also, don't forget to check if the files are successfully opened and to close the files opened.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

Use getline function instead fscanf. Because fscanf can't read the full string which contain the space character

 while ((read = getline(&line, &len, stream)) != -1) 
 {
     printf("Retrieved line of length %zu :\n", read);
     printf("%s", line);
 }

See full detail about getline: http://man7.org/linux/man-pages/man3/getline.3.html

Viet
  • 553
  • 1
  • 4
  • 18