Tag:

刷新输入流C的问题

我无法在这里刷新stdin,有没有办法刷新stdin?如果没有,那么如何使getchar()从用户输入一个字符作为输入,而不是输入缓冲区中scanf留下的“\ n”? ? #include“stdio.h”#include“stdlib.h”int main(int argc,char * argv []){FILE * fp; char another =’y’; struct emp {char name [40]; 年龄; 漂浮bs; }; 结构; if(argc!= 2){printf(“请写1个目标文件名\ n”); } fp = fopen(argv [1],“wb”); if(fp == NULL){puts(“无法打开文件”); 出口(1); } while(another ==’y’){printf(“\ n输入名称,年龄和基本工资”); scanf(“%s%d%f”,e.name,&e.age,&e.bs); 的fwrite(&E,的sizeof(e)中,1,FP); printf(“添加另一条记录(Y / N)”); fflush(标准输入); 另一= getchar函数(); } fclose(fp); 返回0; } 编辑: – 更新的代码,仍然无法正常工作 #include“stdio.h” […]

创建导致字符串的FILE *流

我正在寻找一种方法将FILE *传递给某个函数,以便函数可以使用fprintf写入它。 如果我希望输出在磁盘上的实际文件中出现,这很容易。 但我想要的是将所有输出作为字符串( char * )。 我喜欢的那种API是: /** Create a FILE object that will direct writes into an in-memory buffer. */ FILE *open_string_buffer(void); /** Get the combined string contents of a FILE created with open_string_buffer (result will be allocated using malloc). */ char *get_string_buffer(FILE *buf); /* Sample usage. */ FILE *buf; buf = open_string_buffer(); […]

如何fgets()C中文件的特定行?

所以,我正在尝试找到一种方法来fgets()C中文本文件中的特定行,以将该行的内容复制到更永久的缓冲区中: 基本上,我想知道是否有一种方法可以做到这一点,没有类似于以下代码: FILE *fp; fp = fopen(filename, “r”); char line[256]; char * buffer; int targetline = 10; while( targetline > 0) { fgets(line, 256, fp) } buffer =(char*)malloc(sizeof(char) * strlen(line)); strcpy(buffer, line); 所以基本上我不想遍历文件n-1次只是为了到达第n行……它只是看起来效率不高(而且,这是作业,我需要得到100%哈哈) 。 任何帮助,将不胜感激。

在C中向后读取文本文件

在C中向后读取文件的最佳方法是什么? 我知道一开始你可能会认为这没什么用处,但是大多数日志等都会在文件末尾添加最新的数据。 我想从文件向后读取文本,将其缓冲为行 – 即 ABC 高清 GHI 应该读行ghi , def , abc 。 到目前为止,我尝试过: #include #include void read_file(FILE *fileptr) { char currentchar = ‘\0’; int size = 0; while( currentchar != ‘\n’ ) { currentchar = fgetc(fileptr); printf(“%c\n”, currentchar); fseek(fileptr, -2, SEEK_CUR); if( currentchar == ‘\n’) { fseek(fileptr, -2, SEEK_CUR); break; } else size++; […]