我看到人们最近在很多帖子中试图读取这样的文件.
码
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
char *path = argc > 1 ? argv[1] : "input.txt";
FILE *fp = fopen(path, "r");
if( fp == NULL ) {
perror(path);
return EXIT_FAILURE;
}
while( !feof(fp) ) { /* THIS IS WRONG */
/* Read and process data from file… */
}
if( fclose(fp) == 0 ) {
return EXIT_SUCCESS;
} else {
perror(path);
return EXIT_FAILURE;
}
}
Run Code Online (Sandbox Code Playgroud)
这个__CODE__
循环有什么问题?
我写了这个函数来从文件中读取一行:
const char *readLine(FILE *file) {
if (file == NULL) {
printf("Error: file pointer is null.");
exit(1);
}
int maximumLineLength = 128;
char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);
if (lineBuffer == NULL) {
printf("Error allocating memory for line buffer.");
exit(1);
}
char ch = getc(file);
int count = 0;
while ((ch != '\n') && (ch != EOF)) {
if (count == maximumLineLength) {
maximumLineLength += 128;
lineBuffer = realloc(lineBuffer, maximumLineLength);
if (lineBuffer == NULL) {
printf("Error reallocating space for …
Run Code Online (Sandbox Code Playgroud) 首先,一些背景:我试图从外部文件中获取整数列表并将它们放入数组中.我使用getline逐行解析输入文件:
int lines = 0;
size_t * inputBuffer = (size_t *) malloc(sizeof(size_t));
char * storage = NULL;
Run Code Online (Sandbox Code Playgroud)
我这样叫getline:
getline(&storage, &s, input)
Run Code Online (Sandbox Code Playgroud)
我从getline的man页面听到,如果你提供了size_t*缓冲区,你可以让getline在超过字节分配时为你调整大小.我的问题是,你可以使用这个缓冲区吗?它是否包含您使用getline()读取的所有项目?从这个缓冲区读取是否更简单,或者在将这些整数放入数组时以不同的方式遍历输入?谢谢!
我基本上想打印出我制作的文件中的所有行,但它只是一遍又一遍地循环回到开始,基本上是因为我在函数中设置了fseek(fp, 0, SEEK_SET);
这部分,但我知道否则我将如何放置它以完成所有其他操作行我基本上每次都回到开始。
#include<stdio.h>
#include <stdlib.h>
char *freadline(FILE *fp);
int main(){
FILE *fp = fopen("story.txt", "r");
if(fp == NULL){
printf("Error!");
}else{
char *pInput;
while(!feof(fp)){
pInput = freadline(fp);
printf("%s\n", pInput); // outpu
}
}
return 0;
}
char *freadline(FILE *fp){
int i;
for(i = 0; !feof(fp); i++){
getc(fp);
}
fseek(fp, 0, SEEK_SET); // resets to origin (?)
char *pBuffer = (char*)malloc(sizeof(char)*i);
pBuffer = fgets(pBuffer, i, fp);
return pBuffer;
}
Run Code Online (Sandbox Code Playgroud)
这是我目前的工作