我的程序(如下)寫(與PWRITE())文本PWRITE()寫入到文件,並讀取(與PREAD())從文件。我的問題是pread函數不能從文件中讀取我的文本,關閉函數(程序的最後一部分)有什麼問題?結果在第二部分。我的錯誤在哪裏?閱讀與PREAD(),並在C
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
int main()
{
int fd, nr, nr2, nw, nw2;
char fl_nm[]={"file_io/pwrite.txt"};
char buf_wr[]={"hello everyone this is first text\n"};
char buf_wr2[]={"Did you miss me? Don't afraid\n"};
char buf_rd[120];
char buf_rd2[120];
//open file
fd = open(fl_nm, O_RDWR|O_CREAT, 0777);
nw = pwrite(fd, &buf_wr, strlen(buf_wr), 14);
//error checking
if(fd == -1){
perror("[error in open]\n");
}
else if(nw == -1){
perror("[error in write]\n");
}
else{
/*if open and write process are okey, read first write data
* from file*/
nr = read(fd, &buf_rd, sizeof(buf_rd));
//display succeeded message about first write and open process
printf("[file is opened]\n");
printf("[succeeded write(1) process]\n");
//read process error control
if(nr == -1){
perror("[error in read]\n");
} else{
printf("[reading(1) data] from %s\n", fl_nm);
printf("[%s]\n", buf_rd);
}
}
//second write process.
nw2= pwrite(fd, &buf_wr2, strlen(buf_wr2), 30);
//write error checking
if(nw2 == -1){
perror("[error in write 2]\n");
}else{
/*if write process is correct
* second read process*/
nr2 = read(fd, &buf_rd2, sizeof(buf_rd));
printf("-----------------------------------\n");
printf("[succeeded write(2) process]\n");
printf("[reading(2) data] from %s\n", fl_nm);
printf("[%s]\n", buf_rd2);
}
//close file
close(fd);
//error checking for close process
if(close(fd) == -1){
perror("[error in close]\n");
}else{
printf("[succeeded in close]\n");
}
return 0;
}
結果:
$ gcc pwrite.c -o pwrite
$ ./pwrite
[file is opened]
[succeeded write(1) process]
[reading(1) data] from file_io/pwrite.txt
[]
-----------------------------------
[succeeded write(2) process]
[reading(2) data] from file_io/pwrite.txt
[]
[error in close]
: Bad file descriptor
每[標準](http://pubs.opengroup.org/onlinepubs/9699919799/functions/read:
相反,使用一個循環打印每個字節(),'pread()','write()'和'pwrite()'返回'ssize_t',而不是'int'。 –