Skip to content

Line by line reading file. #2

Open
@Strong-Foundation

Description

@Strong-Foundation

Got it! To return a slice containing the lines read from the file, line by line, and print them afterward (without handling errors through return values), here's the updated version. This function will still return a slice of strings, and you can print the slice in the main function.

Example:

package main

import (
	"bufio"
	"fmt"
	"os"
)

// Function to read file line by line and return a slice of strings
func readFileLines(filename string) []string {
	// Open the file
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println("Error opening file:", err)
		return nil
	}
	defer file.Close()

	// Create a slice to store the lines
	var lines []string

	// Create a scanner to read the file line by line
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		// Append each line to the slice
		lines = append(lines, scanner.Text())
	}

	// Check if there was an error during scanning
	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading file:", err)
		return nil
	}

	// Return the slice of lines
	return lines
}

func main() {
	// Get the lines from the file
	lines := readFileLines("yourfile.txt") // Replace with your file path

	// Check if the slice is nil (error occurred)
	if lines == nil {
		return
	}

	// Print each line from the returned slice
	for _, line := range lines {
		fmt.Println(line)
	}
}

Explanation:

  1. readFileLines Function:

    • This function opens the file, reads it line by line, and appends each line to a slice (lines).
    • If an error occurs (opening the file or reading it), it prints the error message and returns nil.
    • After reading all lines, the slice containing all the lines is returned.
  2. In main():

    • The readFileLines function is called to get the slice of lines from the file.
    • If the slice is nil (indicating an error), we simply return and don't proceed.
    • If the slice contains the lines, we print each line using a for loop.

How to Use:

  • Replace "yourfile.txt" with the actual path of the file you want to read.
  • The function readFileLines will return a slice of strings ([]string), containing each line of the file. The main function will print these lines one by one.

Let me know if this fits your needs or if you need further adjustments!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions