1. 目的:需要把一段字符串倒着输出,并且写入一个文本文档。知识涉及文件IO基础,需要熟练掌握open,write,read等函数及c语言编程基础。
- 步骤
1.写一个swap函数去实现字符串的颠倒,如将hello world变为dlrow olleh;
下面展示函数的代码
。
void str_swap(char *pa)
{
int len=strlen(pa);//计算字符串的有效长度
int left=0,right=len-1;
char temp;//作为一个中间变量,实现前后下标的交换
while(left<right){//交换到中间的位置,left>=right时结束循环;
temp=pa[right];
pa[right]=pa[left];
pa[left]=temp;
left++;
right--;
}
//return pa;
}
2.首先要打开一个文件
int fd,size;
fd=open("./1.txt",O_WRONLY | O_CREAT | O_APPEND,0666);//创建并打开一个文件,文件权限为-rw-rw-rw-
if(fd==-1)
perror("open");//一个出错处理
3.定义一个字符串,并计算它的大小;把它写进文件里面,也就是前面的1.txt。注意: fd作为1.txt的文件描述符,把它当作这个文件就行;
char s[]="hello world!",buf[20];
size=sizeof(s);
int a=write(fd,s,size);
if(a==-1)
perror("write");
4.定义一个数组,把文件的内容读到这个数组里,便于理解和看结果
read(fd,buf,sizeof(buf));
close(fd);
printf("buf:%s\n",buf);
- 最后完整代码奉上
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
void str_swap(char *pa)
{
int len=strlen(pa);
int left=0,right=len-1;
char temp;
while(left<right){
temp=pa[right];
pa[right]=pa[left];
pa[left]=temp;
left++;
right--;
}
//return pa;
}
int main(int argc, char *argv[])
{
int fd,size;
fd=open("./1.txt",O_WRONLY | O_CREAT | O_APPEND,0666);
if(fd==-1)
perror("open:");
char s[]="hello world!",buf[20];
size=sizeof(s);
int a=write(fd,s,size);
if(a==-1)
perror("write");
str_swap(s);
write(fd,s,size);
close(fd);
fd=open("./1.txt",O_RDONLY);
if(a==-1)
perror("write");
read(fd,buf,sizeof(buf));
close(fd);
printf("buf:%s\n",buf);
return 0;
}
补充,文件里面的结果是这样
每执行一次,就会写入一次,下一次是颠倒着写入的