|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +// Con el paquete "os" podemos manejar la apertura, el cierre, la lectura y escritura de archivos, |
| 12 | +// así como la obtención y configuración de atributos de los mismos. |
| 13 | + |
| 14 | +func main() { |
| 15 | + // filename Constante que contiene el nombre del archivo. |
| 16 | + const fileName = "MiguelP-Dev.txt" |
| 17 | + message := []byte("Miguel\n 31 Años.\n Golang.") |
| 18 | + |
| 19 | + // Creamos el archivo para su uso |
| 20 | + file, err := os.Create(fileName) |
| 21 | + if err != nil { |
| 22 | + fmt.Println("Error al crear el archivo.", fileName) |
| 23 | + return |
| 24 | + } |
| 25 | + |
| 26 | + // Garanticemos que el archivo se cierre enventualmente |
| 27 | + defer file.Close() |
| 28 | + |
| 29 | + // Apertura del archivo con permisos de escritura |
| 30 | + file, err = os.OpenFile(fileName, os.O_RDWR, 0644) |
| 31 | + if err != nil { |
| 32 | + fmt.Println("Error abriendo el archivo:", err) |
| 33 | + return |
| 34 | + } |
| 35 | + |
| 36 | + // Escribir contenido en el archivo |
| 37 | + _, writeError := file.Write(message) |
| 38 | + if writeError != nil { |
| 39 | + fmt.Println("Error al escribir en el archivo:", writeError) |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + // Leer el archivo desde el principio |
| 44 | + file.Seek(0, 0) |
| 45 | + buffer := make([]byte, len(message)) |
| 46 | + _, readError := file.Read(buffer) |
| 47 | + if readError != nil { |
| 48 | + fmt.Println("Error al leer el archivo:", readError) |
| 49 | + return |
| 50 | + } |
| 51 | + fmt.Println("Contenido del archivo:", string(buffer)) |
| 52 | + |
| 53 | + // Eliminamos el archivo |
| 54 | + err = os.Remove(fileName) |
| 55 | + if err != nil { |
| 56 | + fmt.Println("error al eliminar el archivo") |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + // Extra |
| 61 | + // Creamos el archivo y controlamos el posible error |
| 62 | + file, err = os.OpenFile(productsFile, os.O_APPEND|os.O_CREATE, 0644) |
| 63 | + if err != nil { |
| 64 | + fmt.Println("Error al crear el archivo Main():", err) |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + err = file.Close() |
| 69 | + if err != nil { |
| 70 | + fmt.Println("Error al cerrar el archivo Main(): ", err) |
| 71 | + } |
| 72 | + |
| 73 | + var productName string |
| 74 | + var productQuantity string |
| 75 | + var productPrice string |
| 76 | + var option uint |
| 77 | + |
| 78 | + for { |
| 79 | + fmt.Println("Selecciona una de las opciones: ") |
| 80 | + fmt.Println("1. Añadir un Producto") |
| 81 | + fmt.Println("2. Consultar un producto") |
| 82 | + fmt.Println("3. Consultar lista de productos") |
| 83 | + fmt.Println("4. Consultar precio unitario de productos") |
| 84 | + fmt.Println("5. Consultar venta total") |
| 85 | + fmt.Println("6. Actualizar un producto") |
| 86 | + fmt.Println("7. Eliminar un producto") |
| 87 | + fmt.Println("8. Salir") |
| 88 | + fmt.Scan(&option) |
| 89 | + |
| 90 | + switch option { |
| 91 | + case 1: |
| 92 | + fmt.Printf("Ingresa el nombre del producto: ") |
| 93 | + fmt.Scan(&productName) |
| 94 | + fmt.Printf("Ingresa la cantidad: ") |
| 95 | + fmt.Scan(&productQuantity) |
| 96 | + fmt.Printf("Ingresa el valor: ") |
| 97 | + fmt.Scan(&productPrice) |
| 98 | + err := pro.AddingProduct(productName, productQuantity, productPrice) |
| 99 | + if err != nil { |
| 100 | + fmt.Println("Error AddingProduct(): ", err) |
| 101 | + } |
| 102 | + case 2: |
| 103 | + fmt.Printf("Ingresa el nombre del producto: ") |
| 104 | + fmt.Scan(&productName) |
| 105 | + err := pro.searchProduct(productName) |
| 106 | + if err != nil { |
| 107 | + fmt.Println("Error searchProduct(): ", err) |
| 108 | + } |
| 109 | + case 3: |
| 110 | + err := pro.listOfProducts() |
| 111 | + if err != nil { |
| 112 | + fmt.Println("Error listOfProducts(): ", err) |
| 113 | + } |
| 114 | + case 4: |
| 115 | + err := pro.totalSaleByProduct() |
| 116 | + if err != nil { |
| 117 | + fmt.Println("Error totalSaleByProduct(): ", err) |
| 118 | + } |
| 119 | + case 5: |
| 120 | + err := pro.totalSaleAmount() |
| 121 | + if err != nil { |
| 122 | + fmt.Println("Error totalSaleAmount(): ", err) |
| 123 | + } |
| 124 | + case 6: |
| 125 | + fmt.Printf("Ingresa el nombre del producto: ") |
| 126 | + fmt.Scan(&productName) |
| 127 | + fmt.Printf("Ingresa la cantidad: ") |
| 128 | + fmt.Scan(&productQuantity) |
| 129 | + fmt.Printf("Ingresa el valor: ") |
| 130 | + fmt.Scan(&productPrice) |
| 131 | + err := pro.updateProduct(productName, productQuantity, productPrice) |
| 132 | + if err != nil { |
| 133 | + fmt.Println("Error updateProduct(): ", err) |
| 134 | + } |
| 135 | + case 7: |
| 136 | + fmt.Println("Ingrese el nombre del producto a eliminar: ") |
| 137 | + fmt.Scan(&productName) |
| 138 | + pro.deleteProduct(productName) |
| 139 | + case 8: |
| 140 | + err := os.Remove(productsFile) |
| 141 | + if err != nil { |
| 142 | + fmt.Println("Error al eliminar el archivo:", err) |
| 143 | + return |
| 144 | + } |
| 145 | + os.Exit(0) |
| 146 | + default: |
| 147 | + fmt.Println("Selecciona una opcion correcta\n") |
| 148 | + } |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +var productsFile = "Productos.txt" |
| 153 | +var tmpFile = "tmp.txt" |
| 154 | + |
| 155 | +type products struct { |
| 156 | + name string |
| 157 | + quantity string |
| 158 | + price string |
| 159 | +} |
| 160 | + |
| 161 | +var pro = products{} |
| 162 | + |
| 163 | +func (p *products) AddingProduct(name, quantity, price string) error { |
| 164 | + |
| 165 | + products, err := search(productsFile) |
| 166 | + if err != nil { |
| 167 | + return err |
| 168 | + } |
| 169 | + |
| 170 | + err = os.Remove(productsFile) |
| 171 | + if err != nil { |
| 172 | + return err |
| 173 | + } |
| 174 | + |
| 175 | + file, err := os.Create(productsFile) |
| 176 | + if err != nil { |
| 177 | + return err |
| 178 | + } |
| 179 | + defer file.Close() |
| 180 | + |
| 181 | + if len(products) > 0 { |
| 182 | + for _, product := range products { |
| 183 | + _, err = file.WriteString(product + "\n") |
| 184 | + if err != nil { |
| 185 | + return err |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + newProduct := strings.ToLower(name) + ", " + quantity + ", " + price + "\n" |
| 191 | + _, err = file.WriteString(newProduct) |
| 192 | + if err != nil { |
| 193 | + return err |
| 194 | + } |
| 195 | + |
| 196 | + err = file.Sync() |
| 197 | + if err != nil { |
| 198 | + return err |
| 199 | + } |
| 200 | + return nil |
| 201 | +} |
| 202 | + |
| 203 | +func (p *products) searchProduct(name string) error { |
| 204 | + products, err := search(productsFile) |
| 205 | + if err != nil { |
| 206 | + return err |
| 207 | + } |
| 208 | + |
| 209 | + for _, product := range products { |
| 210 | + split := strings.Split(product, ", ") |
| 211 | + if strings.ToLower(split[0]) == strings.ToLower(name) { |
| 212 | + fmt.Printf("Nombre: %s, Cantidad: %s, Valor: %s.\n", split[0], split[1], split[2]) |
| 213 | + return nil |
| 214 | + } |
| 215 | + } |
| 216 | + fmt.Printf("Producto %s no encontrado.\n", strings.ToUpper(name)) |
| 217 | + return nil |
| 218 | +} |
| 219 | + |
| 220 | +func (p *products) listOfProducts() error { |
| 221 | + products, err := search(productsFile) |
| 222 | + if err != nil { |
| 223 | + return err |
| 224 | + } |
| 225 | + |
| 226 | + for _, product := range products { |
| 227 | + split := strings.Split(product, ", ") |
| 228 | + fmt.Printf("Nombre: %s, Cantidad: %s, Valor: %s.\n", split[0], split[1], split[2]) |
| 229 | + } |
| 230 | + return nil |
| 231 | +} |
| 232 | + |
| 233 | +func (p *products) deleteProduct(name string) error { |
| 234 | + products, err := search(productsFile) |
| 235 | + if err != nil { |
| 236 | + return err |
| 237 | + } |
| 238 | + |
| 239 | + var newProducts = []string{} |
| 240 | + for _, product := range products { |
| 241 | + splited := strings.Split(product, ", ") |
| 242 | + if strings.ToLower(splited[0]) != strings.ToLower(name) { |
| 243 | + newProducts = append(newProducts, splited[0]+", "+splited[1]+", "+splited[2]) |
| 244 | + } |
| 245 | + } |
| 246 | + |
| 247 | + err = os.Remove(productsFile) |
| 248 | + if err != nil { |
| 249 | + return err |
| 250 | + } |
| 251 | + |
| 252 | + file, err := os.Create(productsFile) |
| 253 | + if err != nil { |
| 254 | + return err |
| 255 | + } |
| 256 | + defer file.Close() |
| 257 | + |
| 258 | + for i := 0; i <= len(newProducts)-1; i++ { |
| 259 | + file.WriteString(newProducts[i] + "\n") |
| 260 | + } |
| 261 | + file.Sync() |
| 262 | + |
| 263 | + return nil |
| 264 | +} |
| 265 | + |
| 266 | +func (p *products) updateProduct(name, quantity, price string) error { |
| 267 | + products, err := search(productsFile) |
| 268 | + if err != nil { |
| 269 | + return err |
| 270 | + } |
| 271 | + |
| 272 | + var newProducts = []string{} |
| 273 | + for _, product := range products { |
| 274 | + splited := strings.Split(product, ", ") |
| 275 | + if strings.ToLower(splited[0]) != strings.ToLower(name) { |
| 276 | + newProducts = append(newProducts, splited[0]+", "+splited[1]+", "+splited[2]) |
| 277 | + } else if strings.ToLower(splited[0]) == strings.ToLower(name) { |
| 278 | + newProducts = append(newProducts, name+", "+quantity+", "+price) |
| 279 | + } |
| 280 | + } |
| 281 | + |
| 282 | + err = os.Remove(productsFile) |
| 283 | + if err != nil { |
| 284 | + return err |
| 285 | + } |
| 286 | + |
| 287 | + file, err := os.Create(productsFile) |
| 288 | + if err != nil { |
| 289 | + return err |
| 290 | + } |
| 291 | + defer file.Close() |
| 292 | + |
| 293 | + for i := 0; i <= len(newProducts)-1; i++ { |
| 294 | + file.WriteString(newProducts[i] + "\n") |
| 295 | + } |
| 296 | + file.Sync() |
| 297 | + |
| 298 | + return nil |
| 299 | +} |
| 300 | + |
| 301 | +func (p *products) totalSaleAmount() error { |
| 302 | + products, err := search(productsFile) |
| 303 | + if err != nil { |
| 304 | + return err |
| 305 | + } |
| 306 | + amounts := []string{} |
| 307 | + for _, product := range products { |
| 308 | + split := strings.Split(product, ", ") |
| 309 | + amounts = append(amounts, split[2]) |
| 310 | + } |
| 311 | + |
| 312 | + var total float64 |
| 313 | + for i := 0; i <= len(amounts)-1; i++ { |
| 314 | + conversion, err := strconv.ParseFloat(amounts[i], 64) |
| 315 | + if err != nil { |
| 316 | + return err |
| 317 | + } |
| 318 | + total += conversion |
| 319 | + } |
| 320 | + fmt.Printf("Total vendido: %v\n", total) |
| 321 | + return nil |
| 322 | +} |
| 323 | + |
| 324 | +func (p *products) totalSaleByProduct() error { |
| 325 | + products, err := search(productsFile) |
| 326 | + if err != nil { |
| 327 | + return err |
| 328 | + } |
| 329 | + |
| 330 | + for i := 0; i <= len(products)-1; i++ { |
| 331 | + splittedProduct := strings.Split(products[i], ", ") |
| 332 | + |
| 333 | + price, err := strconv.ParseFloat(splittedProduct[2], 64) |
| 334 | + if err != nil { |
| 335 | + return err |
| 336 | + } |
| 337 | + |
| 338 | + quantity, err := strconv.Atoi(splittedProduct[1]) |
| 339 | + if err != nil { |
| 340 | + return err |
| 341 | + } |
| 342 | + |
| 343 | + unitaryPrice := price / float64(quantity) |
| 344 | + |
| 345 | + fmt.Printf("Producto: %s, Cantidad total: %v, Precio total: %v, Precio por unidad: %v\n", splittedProduct[0], splittedProduct[2], quantity, unitaryPrice) |
| 346 | + } |
| 347 | + |
| 348 | + return nil |
| 349 | +} |
| 350 | + |
| 351 | +func search(filename string) ([]string, error) { |
| 352 | + file, err := os.OpenFile(filename, os.O_RDONLY, 0644) |
| 353 | + if err != nil { |
| 354 | + return []string{}, err |
| 355 | + } |
| 356 | + defer file.Close() |
| 357 | + |
| 358 | + var products = []string{} |
| 359 | + scanner := bufio.NewScanner(file) |
| 360 | + for scanner.Scan() { |
| 361 | + products = append(products, scanner.Text()) |
| 362 | + } |
| 363 | + |
| 364 | + if err := scanner.Err(); err != nil { |
| 365 | + return []string{}, err |
| 366 | + } |
| 367 | + |
| 368 | + return products, nil |
| 369 | +} |
0 commit comments