Elliot Chance
Elliot Chance

Reputation: 5736

How do I create an instance of *os.File from a string?

I have a string that I need to be a read only file pointer (*os.File). I cannot use strings.NewReader because the function only accepts *os.File. Is this possible?

I realise I could write the string directly to a file and then open it again. But I would like to avoid this step.

Upvotes: 0

Views: 938

Answers (3)

You can use os.NewFile(0, "my-file.txt") this return an *os.File

Upvotes: 0

Stephen Weinberg
Stephen Weinberg

Reputation: 53418

Short answer is that you can't. For this reason, it is generally not recommended in Go to write functions that take an os.File unless you are actually doing a manual syscall or something else that would require an os.File. Instead, your functions should accept an io.Reader or another interface (perhaps containing io.Seeker) depending on what is needed.

If you can modify the place that needs an os.File, that is your best bet. If you cannot and it really only needs a reader, you could use os.Pipe.

With more context, I might be able to give a better recommendation.

Upvotes: 4

jeevatkm
jeevatkm

Reputation: 4781

You can't create *os.File from string. If you can't use io.Reader, best bet is to write the string into temporary file and then use os.Open to get the *os.File.

Upvotes: 1

Related Questions