C语言如何从指定行读取文件
来源:互联网 发布:mac chrome flash插件 编辑:程序博客网 时间:2024/04/29 19:29
在这里我们一共有三个功能,写文件,读文件,从指定行中读取文件,代码比较简单不多加解释。
#include <stdlib.h>#include <string.h>#include <stdio.h>#define MAX_LENTH_OF_LINE 1024FILE* fptr;int WriteToText(){fptr = fopen("test.txt", "w");if (fptr == NULL){printf("Cannot Open file for writing\n");return -1;}for (int i = 0; i < 3; i++){fprintf(fptr, "%d %d %d %d %d %d \n", i + 1, i + 2, i + 3, i + 4, i + 5, i + 6);/*生成文本文件test.txt 文本内容1 2 3 4 5 62 3 4 5 6 73 4 5 6 7 8*/}fclose(fptr);return 1;}int ReadFromText(){fptr = fopen("test.txt", "r");if (fptr == NULL){printf("Cannot Open file for reading\n");return -1;}int a, b, c, d, e, f;for (int i = 0; i < 3; i++){fscanf(fptr, "%d %d %d %d %d %d \n", &a, &b, &c, &d, &e, &f);printf("%d %d %d %d %d %d \n", a, b, c, d, e, f);/*控制台打印出的文本内容1 2 3 4 5 62 3 4 5 6 73 4 5 6 7 8*/}fclose(fptr);return 1;}int SetPositionByLine(FILE *fp, int nLine){int i = 0;char buffer[MAX_LENTH_OF_LINE + 1];fpos_t pos;rewind(fp);for (; i < nLine; i++)fgets(buffer, MAX_LENTH_OF_LINE, fp);fgetpos(fp, &pos);return 0;}int ReadByLine(){char buffer[MAX_LENTH_OF_LINE + 1];FILE *fp;fp = fopen("test.txt", "r");SetPositionByLine(fp, 2);fgets(buffer, MAX_LENTH_OF_LINE, fp);printf("%s\n", buffer);/*读取第三行的内容3 4 5 6 7 8*/fclose(fp);}int splitLineStr(int strNum,char* bufIn,char* bufOut,int* bufLen){ int i = 0; int j = 0; int k = 0; for (; bufIn[i] != 0 && j < strNum; i++){ if (isspace(bufIn[i])){ if (j == 0) { memcpy(bufOut, bufIn, i); k = i + 1; *bufLen = i; } else { memset(bufOut, '\0', sizeof(bufOut)); memcpy(bufOut, bufIn + k, i - k); *bufLen = i - k; k = i + 1; } j++; if (j == strNum) { return 1; } else{ continue; } } } return 1;}void main(){//WriteToText();//ReadFromText();ReadByLine();system("pause");return;}
0 0
- C语言如何从指定行读取文件
- c语言如何从txt文件读取数据
- c语言:读取文件中的指定内容
- 从文件中读取指定的行
- 大文件从指定行开始读取
- C语言读取指定文件夹下面的所有文件
- C语言文件读写操作,从文件读取数据
- C语言如何删除文件中的指定行--更新txt等形式文件
- C语言文件读取
- C语言----文件读取
- C语言读取文件
- C语言读取文件
- 读取文件指定行
- C语言sscanf()函数:从字符串中读取指定格式的数据
- Java中从指定txt读取文件
- c语言读取文件的行
- C语言之按行读取文件
- C语言sscanf()函数:从字符串中读取指定格式的数据&&C语言strtok()函数:字符串分割
- 5.2 多维数组
- 如何使用Docker部署Go Web应用程序
- 5.3 指针与地址
- IP进制转换
- mysql中查询字段为null或者不为null
- C语言如何从指定行读取文件
- java中hashcode()和equals()的详解
- 5.4 指针与地址
- 装完DZ7后,打开ecshop首页出现:Warning: strpos() [function.strpos]: Empty delimiter
- POJ3342 Party at Hali-Bula(树形DP)
- [李景山php]每天laravel-20160828|McryptEncrypter-2
- 5.5 this 指针
- 集合排序
- 5.6 数组与指针的关系