简体   繁体   English

使用文件描述符读取文件

[英]read file using file descriptor

I need to read a file opened like this: 我需要读取一个这样打开的文件:

int outfile = open(*fileName, "w");

using the file descriptor, I'm doing that like this: 使用文件描述符,我这样做是这样的:

char txt[50];
int bytes;  
bytes = read(outfile,txt, 50);

But I'm getting segmentation fault and the application abort, any ideas? 但是我遇到了分段错误,应用程序中止了,有什么想法吗?

Note the second argument to open. 注意打开第二个参数。 It's "w" this seems like it should indicate that you're opening the file for writing. 它是“ w”,这似乎表明您正在打开要写入的文件。 However, my man pages for open indicates that the second argument should be one of: O_RDONLY , O_WRONLY , or O_RDWR . 但是,我打开的手册页指示第二个参数应为以下之一: O_RDONLYO_WRONLYO_RDWR (fopen uses strings like "w", "w+", "r", ... but that's fopen not open). (fopen使用诸如“ w”,“ w +”,“ r”,...之类的字符串,但是fopen无法打开)。 You may be getting lucky that the value of "w" as an int sets you up for writing but you really want to check your return values and probably want to use 您可能很幸运,将“ w”的值作为一个int值可以进行写操作,但是您确实想检查返回值,并且可能想使用

open(*filename, O_RDWR);

to set up the mode for reading and writing. 设置读写模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM