利用标准IO实现读取文件每一行的内容

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
    char *linebuf;
    size_t linesize;
	FILE *fp;
	int count;
	if(argc < 2)
	{
		fprintf(stderr,"Usage.....\n");
		exit(1);
	}
	//从终端命令行参数得去文件
	fp = fopen(argv[1], "r");
	if(fp == NULL)
	{
		perror("fopen_argv[1]");
		exit(1);
	}
    linebuf = NULL;
    linesize = 0;
	while(1)
    {	
        //利用getlien读取文件每一行数据
        if(getline(&linebuf, &linesize, fp) <  0)
            break;
		printf("%s\n",linebuf);
        printf("%d\n",strlen(linebuf));
        //printf("%d\n",linesize);   
    }
	fclose(fp);
	exit(0);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于共享内存涉及到进程间通信,所以需要使用进程相关的函数,比如fork、shmget、shmat等。下面是一个简单的利用共享内存进行文件IO的程序。 ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <fcntl.h> #define SHMSZ 1024 int main(){ int shmid, fd; int *shm, *s; char c; /* 创建共享内存 */ if((shmid = shmget(IPC_PRIVATE, SHMSZ, IPC_CREAT | 0666)) < 0){ perror("shmget"); exit(1); } /* 将共享内存段连接到进程地址空间 */ if((shm = shmat(shmid, NULL, 0)) == (int *)-1){ perror("shmat"); exit(1); } /* 创建文件 */ if ((fd = open("file.txt", O_CREAT|O_WRONLY|O_TRUNC, 0666)) == -1) { perror("open"); exit(1); } /* 创建子进程 */ pid_t pid; pid = fork(); if(pid < 0){ perror("fork"); exit(1); } else if(pid == 0){ // 子进程,写操作 s = shm; /* 从标准输入读取字符 */ while ((c = getchar()) != EOF) { /* 将字符存入共享内存 */ *s++ = c; /* 遇到换行符表示完成一行,写入文件 */ if (c == '\n') { *(shm + SHMSZ - 1) = '\0'; write(fd, shm, SHMSZ); s = shm; } } /* 结束标志 */ *s = '*'; /* 分离共享内存段 */ if(shmdt(shm) == -1){ perror("shmdt"); exit(1); } /* 关闭文件 */ close(fd); exit(0); } else { // 父进程,读操作 /* 等待子进程结束 */ waitpid(pid, NULL, 0); s = shm; /* 从共享内存读取字符 */ while (*s != '*') { putchar(*s++); } putchar('\n'); /* 分离共享内存段 */ if(shmdt(shm) == -1){ perror("shmdt"); exit(1); } /* 关闭文件 */ close(fd); /* 删除共享内存段 */ if(shmctl(shmid, IPC_RMID, 0) == -1){ perror("shmctl"); exit(1); } exit(0); } return 0; } ``` 这个程序实现了一个简单的共享内存读写文件的操作,通过fork创建子进程,子进程利用共享内存读取标准输入,并将每行的字符串写入文件中。父进程等待子进程结束后,从共享内存中读取字符串并输出到标准输出中。程序中涉及到的函数分别是shmget、shmat、shmdt、shmctl等,用于共享内存的连接、分离、删除等操作。该程序仅供参考,实际使用中需要根据需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值