Linux下如何实现文件的简单读写操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计372个文字,预计阅读时间需要2分钟。
请提供您想要修改的伪原创开头内容,我将为您进行改写。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fd = -1; // fd 就是file descriptor,文件描述符
char buf[1000] = {0};
//char writebuf[20] = "l love linux";
int ret = -1;
// 第一步:打开文件
fd = open("linux.txt", O_RDWR);//注意之前自己定义个a.txt
if (-1 == fd) // 有时候也写成: (fd < 0)
{
printf("文件打开错误\n");
}
else
{
printf("文件打开成功,fd = %d.\n", fd);
}
/* // 第二步:读写文件
// 写文件
ret = write(fd, writebuf, strlen(writebuf));
if (ret < 0)
{
printf("write失败.\n");
}
else
{
printf("write成功,写入了%d个字符\n", ret);
}
*/
// 读文件
ret = read(fd, buf, 500);
if (ret < 0)
{
printf("read失败\n");
}
else
{
printf("实际读取了%d字节.\n", ret);
for(int i=0;i<500;i++)
{
if(buf[i]!='.')
{
printf("%c", buf[i]);
}
else
printf(" ");
}
}
// 第三步:关闭文件
close(fd);
return 0;
}
本文共计372个文字,预计阅读时间需要2分钟。
请提供您想要修改的伪原创开头内容,我将为您进行改写。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fd = -1; // fd 就是file descriptor,文件描述符
char buf[1000] = {0};
//char writebuf[20] = "l love linux";
int ret = -1;
// 第一步:打开文件
fd = open("linux.txt", O_RDWR);//注意之前自己定义个a.txt
if (-1 == fd) // 有时候也写成: (fd < 0)
{
printf("文件打开错误\n");
}
else
{
printf("文件打开成功,fd = %d.\n", fd);
}
/* // 第二步:读写文件
// 写文件
ret = write(fd, writebuf, strlen(writebuf));
if (ret < 0)
{
printf("write失败.\n");
}
else
{
printf("write成功,写入了%d个字符\n", ret);
}
*/
// 读文件
ret = read(fd, buf, 500);
if (ret < 0)
{
printf("read失败\n");
}
else
{
printf("实际读取了%d字节.\n", ret);
for(int i=0;i<500;i++)
{
if(buf[i]!='.')
{
printf("%c", buf[i]);
}
else
printf(" ");
}
}
// 第三步:关闭文件
close(fd);
return 0;
}

