How can I insert a string passed through a terminal into a file?
fp=fopen("personas.txt","a");
printf("Introduce tu nombre:\n");
scanf("%s",&nombre);
That is, what do I have to do to put the contents of the variable name in a file?
How can I insert a string passed through a terminal into a file?
fp=fopen("personas.txt","a");
printf("Introduce tu nombre:\n");
scanf("%s",&nombre);
That is, what do I have to do to put the contents of the variable name in a file?
This would be the way to enter the contents of a variable in file Based on your initial code, comments are added to the code:
int main () {
char texto[20];
//abre archivo.
FILE *f = fopen("personas.txt", "w"); //permisos de escritura.
if (f == NULL)
{
printf("Error al abrir archivo!\n");
exit(1);
}else{
printf("Introduce tu nombre:\n");
//obtiene palabra introducida desde teclado.
scanf("%s", nombre);
fprintf(f, "Se introdujo el nombre: %s\n", nombre);
//cierra archivo.
fclose(f);
}
return 0;
}
To write character by character there is a function fputc (int c, File stream)
Being c the character and stream the file. For this you must go through the string with a loop, for example:
char texto[]="Gandalf";
char *p;
int longitud=0;
p = texto;
while (*p != 'char texto[]="Gandalf";
char *p;
int longitud=0;
p = texto;
while (*p != '%pre%') {
longitud++;
fputc( *p, fichero );
p++; /* Vamos a la siguiente letra */
}'
') {
longitud++;
fputc( *p, fichero );
p++; /* Vamos a la siguiente letra */
}'
Remember to close the Stream at the end of the operation with fclose (File stream)
FILE *fp;
fp = fopen ( "fichero.txt", "r+" );
printf("Introduce tu nombre:\n");
scanf("%s",&nombre);
fputs( nombre, fp );
fclose ( fp );
return 0;