Skip to content

Commit

Permalink
move ReadFileNoStat to its own file
Browse files Browse the repository at this point in the history
This allows it to be built on all platforms
Fixes #221.
Also, updates the max size to 512k (instead of 500k) to match the comment.

Signed-off-by: Paul Gier <[email protected]>
  • Loading branch information
pgier committed Oct 7, 2019
1 parent c0c2a8b commit aee1427
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 20 deletions.
38 changes: 38 additions & 0 deletions internal/util/readfile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright 2019 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package util

import (
"io"
"io/ioutil"
"os"
)

// ReadFileNoStat uses ioutil.ReadAll to read contents of entire file.
// This is similar to ioutil.ReadFile but without the call to os.Stat, because
// many files in /proc and /sys report incorrect file sizes (either 0 or 4096).
// Reads a max file size of 512kB. For files larger than this, a scanner
// should be used.
func ReadFileNoStat(filename string) ([]byte, error) {
const maxBufferSize = 1024 * 512

f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()

reader := io.LimitReader(f, maxBufferSize)
return ioutil.ReadAll(reader)
}
20 changes: 0 additions & 20 deletions internal/util/sysreadfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ package util

import (
"bytes"
"io"
"io/ioutil"
"os"
"syscall"
)
Expand Down Expand Up @@ -48,21 +46,3 @@ func SysReadFile(file string) (string, error) {

return string(bytes.TrimSpace(b[:n])), nil
}

// ReadFileNoStat uses ioutil.ReadAll to read contents of entire file.
// This is similar to ioutil.ReadFile but without the call to os.Stat, because
// many files in /proc and /sys report incorrect file sizes (either 0 or 4096).
// Reads a max file size of 512kB. For files larger than this, a scanner
// should be used.
func ReadFileNoStat(filename string) ([]byte, error) {
const maxBufferSize = 1024 * 500

f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()

reader := io.LimitReader(f, maxBufferSize)
return ioutil.ReadAll(reader)
}

0 comments on commit aee1427

Please sign in to comment.