c - 读取文件并将其存储在结构中,以便可以在其他函数中使用

标签 c file struct

所以我正在尝试编写一个程序来读取文件并将其存储到结构中,以便稍后可以将其传递给其他函数进行操作等。但是,当我尝试访问该文件以用于以后的功能时,似乎没有存储/缓冲任何内容。问题似乎出在“void readFile”函数中。这是我到目前为止所拥有的:

示例输入: 玛丽有一只小羊羔,
玛丽有只小羊羔, 羊毛洁白如雪。

我的调试会正确打印出来,但是最后一行会重复。

struct info{
    int numOfLines;
    char lines[];
}

int main (int argc, char * argv[]){

     int words, sentences, syllables;
     int index = 0;
     struct info lines[200];
     FILE* inFile = NULL;
     inFile = findFile(argv[1]);
     readFile(inFile,lines);
     fclose(inFile);
    return 0;
}
FILE* findFile(char fileName[]){

    FILE* fileIn = NULL;
    fileIn = fopen(fileName, "r");

    while(fileIn == NULL){
    printf("That file does not exist or was unable to be found, please enter another\n");
    fgets(fileName,100,stdin);  
    fopen(fileName, "r");
    }

    return fileIn;
}

void readFile(FILE* toRead, struct info lines[]){
     char sentence[200];
     int i = 0;

    while(!feof(toRead)){
         fgets(sentence,300,toRead); //Would this be better than fread()?
         strcpy(lines[i].lines,sentence);
         printf("%s",lines[i].lines);     //*This is a debug statement. The lines are read properly except the last line is printed twice. not sure why. 
         i++;
    }
}

编辑:现在回顾一下,使用指针而不是字符串数组会是更好的主意吗?

最佳答案

所以我会尽力回答你的问题,尽管它有点模糊。 因此,关于您的问题,我不知道您是否正在尝试读出一个充满“信息结构”的文件,或者尝试从文本/bin 文件中将“x”个字符量读入结构中。

首先,我在您的代码中看到了一些一般内容。

  • 此功能FILE* findFile(char fileName[])有点没有必要。据我所知,您正在尝试查看该文件是否存在。您可以通过使用“acces()”来完成此操作,该函数检查调用进程是否访问文件路径名。实现会像这样If(access(pathOfFile, F_OK) == 0){} 。阅读此链接了解更多信息 https://linux.die.net/man/2/access .
  • 以下代码片段char sentence[200]; fgets(sentence,300,toRead); //Would this be better than fread()? ,您声明一个大小为 200 的 char 数组,然后尝试从文件中读取数据,但尝试读取的数量是 300,因此这永远不会起作用,因为您将在数组之外写入。提示阅读“man”页面,您可以通过在 Linux 终端中输入“man fread”来完成此操作,将 fread 替换为其他函数名称。就像“访问”一样。

我想澄清两点。 关于您的问题,我将为您提供一个从文件中读取结构的示例。因为你的问题So I am trying to write a program that will read a file and store into a struct, such that it can be later on passed to other functions for manipulation and whatnot.如果您试图从文件或结构中读取一些字符,则有点模糊。因此,我重写了您的程序,以将充满 INFO 结构的文件中的结构读取到一个数组中,然后您可以使用该数组进行操作。

代码片段将数据从结构文件读取到结构数组

#include <stdio.h>
#include <unistd.h>

#define file_name "Foo_File"

struct INFO{
  char ar[200];
}

int main (int argc, char * argv[]){
  if(access(file_name, F_OK) != 0{
    printf("File does not exist");
    return -1;//Exit program with -1, error
  }
  int structs = get_Amount_Of_Structs(file_name);
  INFO info_array[structs];//Make an array of info structs, same amount of structs as in file
  for(int i = 0; i < structs; i++){
    readDataStructFromFile(file_name, info_array, i);
  }
  return 0;
}

/*
  This function will calculate the total byte size of the     file by diving this through the byte size of one struct     you are able to know the amount of structs. 
*/
int get_Amount_Of_Structs(char* filename)
{
	FILE* fp = fopen(filename, "r");
	if(fp == NULL){//If File pointer is null opening failed
		return -1;
  }
	fseek(fp, 0L, SEEK_END);
	int amountOfStructs = ftell(fp)/sizeof(INFO);
	fseek(fp, 0L, SEEK_SET);
	fclose(fp);
	return amountOfStructs;
}

/*
  This function reads a struct from a file at the position     "pos" by slight modification you can make it read the       whole file into a pointer that points to an array of INFO   structs
*/
int readDataStructFromFile(char* filename, INFO* data, int pos)
{
	FILE* fp = fopen(filename, "r");
	if(fp == NULL)
	{
		fclose(fp);
		return -1;
	}
	fseek(fp, (pos * sizeof(INFO)), SEEK_SET);
	int rv = fread(data, sizeof(INFO), 1, fp);
	fclose(fp);
	if(rv == 1)
	{
		return 0;
	}
	return -1;
}

我希望这至少可以帮助您解决代码问题。关于“fgets vs fread”问题已经由另一个问题解决了。 希望我能为您的问题提供更完整的答案,但有点含糊。

附:如果社区中的任何人发现我的代码/解释中的错误,请随时编辑或指出我的错误。我是一名学生,所以总有一些东西需要学习。

关于c - 读取文件并将其存储在结构中,以便可以在其他函数中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42284423/

相关文章:

templates - 用模板初始化结构

c++ - 在socket编程的select()中重新启动定时器

php - 在编译期间检测 PHP 是否正在使用给定的扩展名进行编译

java - find WithinHorizo​​n 方法返回 null

SharePoint - 通过 VBScript 自动发布和检索文件

c++ - 在结构图上使用 find(),得到 "has no member named XXX"

c++ - 今天使用二合字母和三合字母吗?

c - 如何在 C 中正确初始化此哈希表实现? (出现段错误)

java - Java中基于标题写入csv/excel

c - 将两个 C 结构打包成一个 uint8_t 指针以写入 DataFlash