-1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv){

FILE *fp;
if((fp=fopen("Example.txt", "r"))== NULL){
    printf("Errore apertura file");
    exit(0);
}
char s[50];
int i=0;
while(!feof(fp)){
if(!feof(fp)){
s[i++]=fgetc(fp);
    }
}
s[i]='\0';
fclose(fp);
char nome[20];
printf("Inserisci il nome che vuoi dare al file di uscita\n");
//fgets(nome,20,stdin);
scanf("%s",& nome);
char tipo[5]=".txt";
strcat(nome,tipo);
if((fp=fopen(nome,"w"))== NULL){
    printf("Errore apertura file");
    exit(0);
}
fputs(s, fp);
fclose(fp);
return 0;  
}

The output file over the string is even printed an abnormal character, how can I not see it? The output is "string"+'ÿ'` The problem is only in the output file and not in the capture.

  • It has to be `scanf("%s", nome);` – John Strood Nov 26 '16 at 19:01
  • And *never* use `feof`. Always check for `EOF` manually. – John Strood Nov 26 '16 at 19:05
  • See [`while (!feof(file))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) for a discussion of why using `feof()` is wrong. What you are seeing is normal behaviour for a code set such as CP1252 or ISO 8859-1 where code point 0xFF is U+00FF, LATIN LOWER CASE LETTER Y WITH DIAERESIS (ÿ). You shouldn't assign the result of `fgetc(fp)` to a `char`; you should check whether the `int` value is EOF before using it as a character. – Jonathan Leffler Nov 26 '16 at 21:37

1 Answers1

0

Your input loop should be:

char s[50];
int i=0;
int c;
while (i < (50 - 1) && (c = fgetc(fp)) != EOF)
    s[i++] = c;
s[i] = '\0';

Or even:

char s[50];
int i;
int c;
for (i = 0; i < (50 - 1) && (c = fgetc(fp)) != EOF; i++)
    s[i] = c;
s[i] = '\0';

These avoid buffer overflow and do not try to store EOF in the array s. They also doesn't use feof(); you seldom need to use it, and when you do, it is after a loop has ended and you need to distinguish between EOF and a read error (see also ferror()).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278