En este artículo, encontrará una lista de ejemplos para manejar operaciones de entrada / salida de archivos en la programación C.
Para comprender todos los programas en esta página, debe tener el conocimiento de los siguientes temas.
- Matrices C
- Punteros C
- Relación de matriz y puntero
- E / S de archivos
Ejemplos de archivos C
1. Programa en C para leer el nombre y las notas de n números de estudiantes y almacenarlos en un archivo.
#include int main() ( char name(50); int marks, i, num; printf("Enter number of students: "); scanf("%d", &num); FILE *fptr; fptr = (fopen("C:\student.txt", "w")); if(fptr == NULL) ( printf("Error!"); exit(1); ) for(i = 0; i < num; ++i) ( printf("For student%dEnter name: ", i+1); scanf("%s", name); printf("Enter marks: "); scanf("%d", &marks); fprintf(fptr,"Name: %s Marks=%d ", name, marks); ) fclose(fptr); return 0; )
2. Programa en C para leer el nombre y las marcas de un número n de estudiantes y almacenarlos en un archivo. Si el archivo se cierra anteriormente, agregue la información al archivo.
#include int main() ( char name(50); int marks, i, num; printf("Enter number of students: "); scanf("%d", &num); FILE *fptr; fptr = (fopen("C:\student.txt", "a")); if(fptr == NULL) ( printf("Error!"); exit(1); ) for(i = 0; i < num; ++i) ( printf("For student%dEnter name: ", i+1); scanf("%s", name); printf("Enter marks: "); scanf("%d", &marks); fprintf(fptr,"Name: %s Marks=%d ", name, marks); ) fclose(fptr); return 0; )
3. Programa en C para escribir todos los miembros de una matriz de estructuras en un archivo usando fwrite (). Lea la matriz del archivo y muéstrela en la pantalla.
#include struct student ( char name(50); int height; ); int main()( struct student stud1(5), stud2(5); FILE *fptr; int i; fptr = fopen("file.txt","wb"); for(i = 0; i < 5; ++i) ( fflush(stdin); printf("Enter name: "); gets(stud1(i).name); printf("Enter height: "); scanf("%d", &stud1(i).height); ) fwrite(stud1, sizeof(stud1), 1, fptr); fclose(fptr); fptr = fopen("file.txt", "rb"); fread(stud2, sizeof(stud2), 1, fptr); for(i = 0; i < 5; ++i) ( printf("Name: %sHeight: %d", stud2(i).name, stud2(i).height); ) fclose(fptr); )