Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Struct y manejo de archivos

25/27
Recursos

Creación y apertura de archivos
Parámetros para la función fopen():

  • ““rb””: Abre un archivo en modo binario para lectura, el fichero debe existir.
  • ““w””: Abrir un archivo en modo binario para escritura, se crea si no existe o se sobreescribe si existe.

Aportes 71

Preguntas 11

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Una pequeña aportación:

  1 #include <stdio.h>
  2 
  3 struct PersonalData {
  4   char first_name[20];
  5   char last_name[20];
  6   int age;
  7 };
  8 
  9 int main(){
 10   struct PersonalData me;
 11 
 12   printf("Vamos a leer los datos:\n");
 13   printf("Digita tu nombre:\n");
 14   gets(me.first_name);
 15   printf("Digita tu primer apellido\n");
 16   gets(me.last_name);
 17   printf("Finalmente digita tu edad\n");
 18   scanf("%i", &me.age);
 19 
 20   printf("Hola %s\n", me.first_name);
 21   printf("Tu apellido es %s\n", me.last_name);
 22   printf("Tu edad es %i\nAdios (: \n", me.age);
 23 }

Se llama Programación Orientada a Objetos, también existen las clases, tienen sutiles diferencias.

  1 #include <stdio.h>
  2 
  3 int main(){
  4   FILE *archive;
  5 
  6   archive = fopen("prueba.dat", "w");
  7                   
  8   if (archive != NULL){
  9     printf("El archivo se ha creado exitosamente\n");
 10     fclose(archive);
 11   }else{
 12     printf("El archivo no se ha creado :(\n");
 13   }
 14 
 15 }

Resumen:

Si necesitamos combinar dos o mas tipos de daots para crear nuestro propio tipo de dato personalizado usamos:

struct {
} nombre-de-mi-estructura;

Podemos agregar cualquier cantidad de variables dentro para asi creat nuestro tipo como:

struct {
char nombre[10];
int edad;
float peso;
char sexo;
} PERSONA;

En nuestro programa podemos usar ahora una variable de tipo persona:

PERSONA persona1;

Y para definir su contenido usamos puntos:

persona1.edad = 22;

Para crear un archivo o abrir ya existente usamos:
FILE archivo = fopen( “nombre-del-archivo.csv”, “w” );
/

Donde ‘w’ es el modo que queremos usar para manipular ese archivo. Puede ser w de write o escribir. r para read o leer. a para append o agregar contenido al final del archivo
*/

Despues de haber usado el archivo debemos de “cerrar” el archivo. Por eso usamos: fclose(archivo);

  • El estándar de C contiene varias funciones para la edición de ficheros, éstas están definidas en la cabecera stdio.h y por lo general empiezan con la letra f, haciendo referencia a file.

  • Adicionalmente se agrega un tipo FILE, el cual se usará como apuntador a la información del fichero. La secuencia que usaremos para realizar operaciones será la siguiente: _

  • Crear un apuntador del tipo FILE *
    Abrir el archivo utilizando la función fopen y asignándole el resultado de la llamada a nuestro apuntador.
    Hacer las diversas operaciones (lectura, escritura, etc).

  • Cerrar el archivo utilizando la función fclose.

📑 El manejar archivos nos permitirá crear archivos, escribir y leer información dentro de los mismos.



En mi caso uso mac no me deja el archivo en la carpeta, me la deja en la raíz de mi equipo.

fopen
Esta función sirve para abrir y crear ficheros en disco.
fclose
Esta función sirve para poder cerrar un fichero que se ha abierto.

dos puntos por termina de ver el video :v

Código de la clase:

Abrir/crear un archivo para escritura:

FILE *filePointer;
filePoint = fopen("nombrearchivo.ext", "w");

...

fclose(filePoint);
struct personalData
{
    char name[20];
    char lastName[20];
    int age;
};

int main()
{
    printf("Estructura de Datos\n");
    struct personalData person;

    printf("Leer los datos que se encuentran en mi struct\n\nIngresa el nombre:\t");
    gets(person.name);

    printf("\nIngresa el apellido:\t");
    gets(person.lastName);

    printf("\nIngresa la edad:\t");
    scanf("%i", &person.age);

    printf("\nVerificacion de datos\n");
    printf("%s \n", person.name);
    printf("%s \n", person.lastName);
    printf("%i \n", person.age);

  return 0;
}```

Interesante, en que casos prácticos o escenarios actuales podría utilizarse ?

Este es mi codigo la parte en que le da los datos y los imprime loshice funciones

Nota: El operador -> que uso es el equivalente a (*apuntador).variableDentroDeStruct

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


struct PersonalData{
    char first_name[20];
    char last_name[20];
    int age;
};

void fillData(struct PersonalData *ptr_me);
void printData(struct PersonalData *ptr_me);

int main(){
    struct PersonalData me;
    fillData(&me);
    printData(&me);
    return 0;
}


void fillData(struct PersonalData *ptr_me){
    printf("Enter your first name:\t");
    scanf("%s", ptr_me->first_name);
    printf("Enter your last name:\t");
    scanf("%s", ptr_me->last_name);
    printf("Enter your age:\t");
    scanf("%d", &ptr_me->age);
}

void printData(struct PersonalData *ptr_me){
    printf("Your first name is:\t%s\n", ptr_me->first_name);
    printf("Your last name is:\t%s\n", ptr_me->last_name);
    printf("Your age is:\t%d\n", ptr_me->age);
}

Muy interesante el tema de manejo de archivos

(

ME SALIO VIEN

Que divertido son los structs, apenas esta comenzando lo interesante y ya casi se termina el curso 😦

Creación y apertura de archivos
⭐️
Parámetros para la función fopen():
🤖🤖🤖
““rb””: Abre un archivo en modo binario para lectura, el fichero debe existir.
🤖🤖🤖
““w””: Abrir un archivo en modo binario para escritura, se crea si no existe o se sobreescribe si existe.

Buen dia campeon. si estas en Mac para compilar directamente en visual studio code, basta con teclear command + r y se compila en programa.

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

int main() {
  printf("\nCreate a file!\n");

  FILE *createFile;

  createFile = fopen("test001.txt", "w");

  if (createFile != NULL) {
    printf("file created successfully. open the folder container\n");
    fclose(createFile);
  } else {
    printf("The file has not been created");
  }

  return 0;
}

Vaya vaya, Struct es como un objeto que se crea en JavaScript, donde instancias todo por medio del this… Bueno segun yo xD

Ese este progrma incorporando el sexo y la estatura en la estructura 😆 :

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

struct datosPersonales
{
    char firstName [30];
    char lastName [30];
    char sexo;
    int edad;
    float estatura;
};

int main(int argc, char const *argv[])
{
    printf("Estructuras de datos en C \n\n");
    struct datosPersonales persona;
    printf("Ingrese su nombre\n");
    if (fgets(persona.firstName, sizeof persona.firstName, stdin) != NULL)
    printf("Escriba su apellido\n");
    if (fgets(persona.lastName, sizeof persona.lastName, stdin) != NULL)
    printf("Digite su sexo: \n m: para masculino \n f: para femenino \n");
    scanf(" %c", &persona.sexo);
    printf("Ingrese su edad \n");
    scanf("%d", &persona.edad);
    printf("Ingrese su estatura en decimal\n");
    scanf("%f", &persona.estatura);

    printf("Su primer nombre: \t %s \n", persona.firstName);
    printf("Su primer Apellido: \t %s \n", persona.lastName);
    printf("Su sexo: \t %c \n", persona.sexo);
    printf("Su edad: \t %d \n", persona.edad);
    printf("Su estatura: \t %.2f metros \n", persona.estatura);
    return 0;
}

Una imagen de muestra ❤️

El código pero con la escritura del archivo funcionando:

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

typedef struct {
    char name[16];
    char last_name[16];
    uint16_t age;
} PersonalData;

PersonalData read_data();
void dump_data(PersonalData* data);
void show_data(PersonalData* p);

int main() {
    PersonalData data = read_data();
    show_data(&data);
    dump_data(&data);
    return EXIT_SUCCESS;
}

PersonalData read_data() {
    PersonalData data;
    printf("You name: ");
    scanf("%s", &data.name);
    fflush(stdin);
    printf("You lastname: ");
    scanf("%s", &data.last_name);
    fflush(stdin);
    printf("You age: ");
    scanf("%d", &data.age);
    fflush(stdin);
    return data;
}

void show_data(PersonalData* data) {
    printf("{name: %s, lastname: %s, age: %d}\n", data->name, data->last_name, data->age);
}

void dump_data(PersonalData* data) {
    puts("Saving data...");
    FILE* file = fopen("dates.dat", "w");
    if (file != NULL) {
	    fprintf(file, "Name: %s\n", data->name);
	    fprintf(file, "Last name: %s\n", data->last_name);
	    fprintf(file, "Age: %d\n", data->age);
	    puts("Data saved successfully :)");
    } else {
	    puts("Error! Could not open file :(");
    }
    fclose(file);
}

Notes

Struct and File Creation

Basic handling of files in C

https://www.geeksforgeeks.org/basics-file-handling-c/

Creating and opening

For opening a file, fopen function is used with the required access modes. Some of the commonly used file access modes are mentioned below.File opening modes in C:

  • “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
  • “rb” – Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
  • “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
  • “wb” – Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
  • “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
  • “ab” – Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created.
  • “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
  • “rb+” – Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
  • “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file.
  • “wb+” – Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
  • “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
  • “ab+” – Open for both reading and appending in binary mode. If the file does not exist, it will be created.
fopen("Nombre_archivo.extensión" "w");
fclose(archivo);

Structs

A struct in the C programming language is a composite data type declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the same address.

struct people
{
	char name[10];
	int id[5]
	float salary;
};

struct: struct keyword

people: structure tag

code within brackets: Members

If you want to call that struct within your code you should do it with the following structure

int main()
{
	struct people person;
	person.name = "Jonathan";
	person.id = 10301230;
	person.salary = 300.5;
}

Struct es igual a un objeto? o que lo diferencia?

Excelente, solo que el archivo no tiene contenido.

Excelente Maestra!

mi codigo:

<
#include <stdio.h>
#include <stlib.h>

struct PersonalData
{
char name[20];
char lastName[20]
int age;
};

int main ()
{
printf(“Estructuras de Datos!\n”);

struct PersonalData person;

printf("leer datos: \n");
printf("ingresar nombre: \n");
gets(person.name);

printf("ingresar apellido: \n");
gets(person.lastName);

printf("ingresar edad: \n");
scanf("%i", &person.age);

printf("%s\n", person.name);
printf("%s\n", person.lastName);
printf("%s\n", person.age);

}

hola cuanto es el porcentaje para aprobar el curso, porque saque 8.93 y no aprobe

  • Las estructuras struct son conjuntos de datos que aceptan diferentes tipos de variables.

Muchas Gracias que buen contenido

Es muy útil esta clase

Excelente

Muy buena explicación sobre struct y manejo de archivos .

En mi caso, he tenido que colocar toda la ruta hasta la carpeta donde se encuentra el archivo. Inicialmente me creaba el archivo en la raíz.

Otra forma que no conocía para crear archivos, se parece mucho a linux.

Gracias

Bastante interesante!!

Ejemplo de estructura

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

struct Datos
	{
		char nombre[30];
		int edad;
		char genero;
	};
	
int main()
{
	
	struct Datos Persona1;
	//se crea una estructura llamada persona1 que tiene todos los atributos que están dentro de la estructura
	
	printf("Introduzca los datos\n");
	printf("Nombre\n");
	gets(Persona1.nombre);
	printf("Edad\n");
	scanf(" %i", &Persona1.edad);
	printf("Genero M o F\n");
	scanf(" %c", &Persona1.genero);
	//Se asignan valores al nombre, edad y genero de la persona1
	
	printf("Datos de la persona:\n");
	printf("Nombre: ");
	puts(Persona1.nombre);
	printf("Edad: %i \n", Persona1.edad);
	printf("Genero: %c\n", Persona1.genero);
	//Se imprimen los valores de la persona1
		
	return 0;
}```

Ejemplo de estructura de datos

<code>
#include <stdio.h>

struct personalData{
    char name[20];
    char apellido[20];
    int edad;
};

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Manejo de archivos \n");
    
    struct personalData person;
    
    printf("Leer datos \n");
    printf("Ingresar nombre: \n");
    gets(person.name);
    
    printf("Ingresar apellido: \n");
    gets(person.apellido);
    
    
    printf("Ingresar edad: \n");
    scanf("%i", &person.edad);
    
    printf("Imprimir datos: \n");
    printf("%s \n", person.name);
    printf("%s \n", person.apellido);
    printf("%i \n", person.edad);
    
    return 0;
}

Excelente maestra!

Muchas gracias por la explicacion quedo super claro el struct

Ejercicio en clase entendido:

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

struct personalData
{
    char name[20];
    char lastName[20];
    int age;
};

int main()
{
    printf("Archivos! Crear un archivo \n");

    struct personalData person;
    printf("Leer los datos: \n");
    printf("Ingresar nombre: ");
    gets(person.name);
    printf("Ingresar apellido: ");
    gets(person.lastName);
    printf("Ingresar edad: ");
    scanf("%i", &person.age);

    printf("Imprimir datos: ");
    printf("%s ", person.name);
    printf("%s", person.lastName);
    printf(", tiene %i años de edad\n", person.age);

    return 0;
}

Resultado:

Archivos! Crear un archivo
Leer los datos:
Ingresar nombre: Ricardo
Ingresar apellido: Rojas
Ingresar edad: 21
Imprimir datos: Ricardo Rojas, tiene 21 a±os de edad

Process returned 0 (0x0)   execution time : 7.779 s
Press any key to continue.

Creacion de archivos dentro del directorio de ejecucion

#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <string.h>

FILE create_file(char[PATH_MAX]);

int main() {
    printf("*** Files creation ***\n");
    char cwd[PATH_MAX];//current working directory
    if (getcwd(cwd, sizeof(cwd)) != NULL) {
        printf("CWD: %s\n", cwd);
        char filename[PATH_MAX];
        strcpy(filename, cwd);
        strcat(filename, "/fsociety.dat");
        FILE hack_file = create_file(filename);
    }
    return 0;
}


FILE create_file(char name[PATH_MAX]) {
    return *fopen(name, "w");
}

genial

Estupenda clase no sabía que esta era la forma para crear archivos en C, muchas gracias instructora Daniela.

Excelente explicación! 👌

Esta es de las clases mas interesantes del curso hasta ahora. Excelente!

Buena clase!

super 😃

Hola 😃

getc que recibe?

Gracias.

genial

Interesante

genial!

Excelente!

Buena clase! Este es el paso inicial a la programación orientada objetos!

Excelente clase

¿No hay forma de imprimir toda la estructura en lugar de ir por partes?

Y yo que pensaba que C no tenía nada de programación orientada a objetos.

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

int main()
{
    printf("Archivos!\n");

    FILE *archivo;

    archivo = fopen("archivo001.dat", "w");

    if(archivo != NULL){
        printf("El archivo se a creado existosamente");
        fclose(archivo);
    }
    else {
        printf("Error al crear archivo");
        return -1;
    }

    return 0;
}

Creación, apertura y cierre

#include <stdio.h>


struct personsalData {
    char name [20];
    char lastname[20];
    int age;
    
};


int main()
{
    printf("Hello World");
    struct personsalData person;
    
    printf("leer los datos: \n");
    printf("ingresar nombre: \n");
    gets(person.name);
     printf("ingresar apellido: \n");
    gets(person.lastname);
     printf("ingresar edad: \n");
    scanf("%i", &person.age);
    
    printf("imprimir datos: \n");
    printf("%s\n",person.name);
    printf("%s\n",person.lastname);
    printf("%i\n",person.age);
    
    return 0;
}

Struct 😄

<struct personalData
{
  char name[20];
  char lastName[20];
  int age;
};

int main()
{
  printf("ESTRUCTURA DE DATOS:\n\n");
  struct personalData person;
  printf("Ingresaremos los datos al struct:\n\n");

  printf("Ingresa tu nombre:\n");
  gets(person.name);
  printf("Ingresa el apellido:\n");
  gets(person.lastName);
  printf("ingrese su edad:\n");
  scanf("%i", &person.age);

  printf("\nDatos ingresados al struct:\n");
  printf("name: %s\n", person.name);
  printf("lastName: %s\n", person.lastName);
  printf("age: %i\n", person.age);

  return 0;
}>

Creando archivos 😄

<int main()
{
    printf("ARCHIVOS! \ncreando archivo\n");

    FILE *archivo;
    archivo = fopen("archivo_Creado.dat", "w");

    if(archivo != NULL)
    {
     printf("El archivo ha sido creado\n");
     printf("puedes verlo en tu carpeta\n");
    }
    else
    {
     printf("El archivo no se ha creado");
    }
    return 0;
}
>

Después de que lo practicas queda mucho mas claro

Como dato curioso: la programación estructurada se usaba antes de que fuera creada la POO (Programación Orientada a Objetos). La estructura Struct es la base para lo que después serían las clases y los objetos. Dicho con otras palabras, Struct es como un objeto primitivo.

Si estan programando en Ubuntu, al principio no me salia el archivo, pero despues utilice el comando " ll "
y me salieron 😄

Mucha atencion esto es el inicio, a POO :3, suerte a todos y saludos.