c语言 txt文件读写的代码!!!!

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c语言 txt文件读写的代码!!!!相关的知识,希望对你有一定的参考价值。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()

FILE* fp = fopen("C:\\Users\\pengchao.li\\Desktop\\test.txt","r+");
char* buf = new char[512];
memset(buf,0,512*sizeof(char));
//读文件
fread(buf,1,5,fp);//指定大小读取
printf("%s\n",buf);
fgets(buf,100,fp);//读取一行
printf("%s\n",buf);
//写文件
char* tmp = "abcefg";
int num = 0;
num = fwrite(tmp,strlen(tmp),1,fp);
//文件位置指针操作
int pos = 0;
pos = ftell(fp);//获取当前位置
fseek(fp,0,SEEK_SET);//设置位置
//一般以上三种操作的合理组合,就够你读写文件了

return 0;
参考技术A 建议你自己看书。 参考技术B 这个真是不难,百度以下 一大片啊

C语言如何读取txt文件里边的数据

项目需要处理txt文件里边的数据,数据来自verilog 算法仿真。
这里举例数据如下:
11.txt
\'C语言如何读取txt文件里边的数据_#include\'
fscanf() 和 fprintf() 函数与前面使用的 scanf() 和 printf() 功能相似,都是格式化读写函数,两者的区别在于 fscanf() 和 fprintf() 的读写对象不是键盘和显示器,而是磁盘文件。
int fscanf ( FILE *fp, char * format, … );
int fprintf ( FILE *fp, char * format, … );

fp 为文件指针,format 为格式控制字符串,… 表示参数列表。

FILE *fp;
int i, j;
char *str, ch;
fscanf(fp, "%d %s", &i, str);
fprintf(fp,"%d %c", j, ch);

示例代码:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 1024


int main()
{
   int buf[MAX_LINE];
   int i;
   FILE *fp=fopen("11.txt","r");
   int len;
   if(fp==NULL) {
     printf(" Open file Error !\\n");
     exit(0);
   }

    for(i=0;i<10;i++){

    fscanf(fp,"%d \\n",&buf[i]);
  }

   printf("%d\\n",buf[0]);

   return 0;
}

运行结果:
ubuntu:~/C/CEX/ex7_file_read$ ./change
233441
ubuntu:~/C/CEX/ex7_file_read$

以上是关于c语言 txt文件读写的代码!!!!的主要内容,如果未能解决你的问题,请参考以下文章

C语言 文件读写综合案例:读取LOL信息

R语言读写最灵活的文件——txt文件

QT读写文件的问题

读写txt文件

如何用C语言读写文件

Python代码中打开txt文件(非读写)