c - 将不需要的数据保存到错误文件

标签 c function pointers if-statement struct

您好,我目前有一段代码可以从文件中获取名称,然后将其保存到另一个文件中。

但是我现在想将任何无效信息保存到一个固定的错误文件中,并且想知道我将如何处理它

我的代码:

结构:

struct Person{
    char fName[16];     //string to store the persons first name
    char lName[21];     //string to store the persons last name
};

主要

int main(){
    int recordCount = 0;    //used to keep track of the number of records currently in memory
    struct Person *records;

    records = malloc(sizeof(struct Person));

    records = open(&recordCount, records);
    records = addRecord(&recordCount, records);
    save(recordCount, records);
    return 0;                   //End the program and return 0 to the operating system
}

打开(&recordCount,记录)函数:

struct Person* open(int *rCount, struct Person *records){
  FILE *recordFile;
  char fileName[30] = {'\0'};
  int i = *rCount;
  char test;


  puts("Enter a filename to open :");
  scanf("%s", fileName);

  if((recordFile = fopen(fileName,"r"))==NULL){
      printf("Couldn't open the file: %s\n",fileName);
      exit(1);
  }
  else{

      test = fscanf(recordFile,"%s %s", records[i].fName,records[i].lName);
      while(test!= EOF){
          i++;
          records = realloc(records,(i+1)*sizeof(struct Person));
          test = fscanf(recordFile,"%s %s", records[i].fName,records[i].lName);
      }
      fclose(recordFile); // close the file
  }
  *rCount = i;
  return records;    //add i (records read from the file) to rCount (the current record count)
}

addRecord(&recordCount, 记录) 函数

struct Person* addRecord(int* rCount, struct Person *records){

int valid = 0;  //used to indicated valid input
int length = 0; //used to store the string lengths
int i = 0;    //used in the for loops
char fNameTest[16];     //temporary storage of input to be checked before adding to records
char lNameTest[21];     //temporary storage of input to be checked before adding to records

//Checking the length of data input for fName
do{
    length = strlen(fNameTest);
    if(length < 16){
        for(i=0;i<=length;i++)                      
            records[*rCount].fName[i] = fNameTest[i]; //if correct insert the record at the index determined by rCount
        valid=1;
    }
    else{

        valid = 0;
    }

}while(valid!=1);

//Checking the length of data input for lName
do{
    length = strlen(lNameTest);
    if(length < 21){
        for(i=0;i<=length;i++)                    
            records[*rCount].lName[i] = lNameTest[i]; //if correct insert the record at the index determined by rCount
        valid=1;
        (*rCount)++;                                   //At this point ID,fName and lName have been stored so increment rCount
    }
    else{

        valid = 0;
    }

}while(valid!=1);


records = realloc(records,((*rCount)+1)*sizeof(struct Person));
return records;  //return rCount as the new updated recordCount
}

保存(记录计数,记录)函数

void save(int rCount, struct Person *records){
  FILE *recordFile;                 //file handle
  char fileName[30] = { '\0'};      //string to store the file name
  int i;

  puts("Enter a filename to save the records :");   //ask the user for the filename
  scanf("%s", fileName);                            //store the filename: data input should be checked
                                                    //here in your program

  //try and open the file for writing and react accordingly if there is a problem
  if((recordFile = fopen(fileName,"w"))==NULL){
      printf("Couldn't open the file: %s\n",fileName);
  }
  else{ //the file opened so print the records array of Person's to it
      for(i=0;i<rCount;i++){
          fprintf(recordFile,"%s %s\n",records[i].fName,records[i].lName);
      }
      fclose(recordFile);   //close the file
      printf("Records saved to file: %s\n",fileName);
  }

}

我正在考虑删除 addRecords 函数中的 do-while 循环并用 if 语句替换它们。最后是一个 if 语句来检查 valid 的值。然后如果 valid=0 指向一个函数或直接将错误文件保存在那里。

但是我不确定这是否是最好的方法(或者我的思考过程是否可行)并且想知道是否有人可以提供帮助。

编辑:决定添加我正在处理的数据类型,以防有人想要创建 .txt 并运行程序

Bob Jones
Franklin Davies
James Donut

编辑按照下面的答案我更新了我的代码(下面编辑的部分)

编辑保存函数

void save(int rCount, struct Person *records){
  FILE *recordFile;                 //file handle
  char fileName[30] = { '\0'};      //string to store the file name
  int i;

  puts("Enter a filename to save the records :");   //ask the user for the filename
  scanf("%s", fileName);                            //store the filename: data input should be checked
                                                    //here in your program

  //try and open the file for writing and react accordingly if there is a problem
  if((recordFile = fopen(fileName,"w"))==NULL){
      printf("Couldn't open the file: %s\n",fileName);
  }
  else{ //the file opened so print the records array of Person's to it

char fileName[sizeof (struct Person) * 2];  // twice needed size

while (fgets(fileName, sizeof fileName, recordFile) != NULL) {
struct Person P;

int n;  // Save index where scanning stopped
int cnt = sscanf(fileName,"%15s%21s %n", P.fName, P.lName, &n);
if (cnt != 2 || fileName[n]) {
  errorLine(fileName);
  // do not increment i;
} else {
  // Good to keep
  // realloc memory as needed here
  records[i] = P;
  i++;
  }

}

错误线函数:

void errorLine(char *fileName)
{
FILE *errorFile;

  //try and open the file for writing and react accordingly if there is a problem
  if((errorFile = fopen("error.txt","w"))==NULL){
      printf("Couldn't open the file:\n");
  }
  else{ //the file opened so print the records array of Person's to it
      for(i=0;i<rCount;i++){
          fprintf(errorFile,"%i %s %s\n",records[i].fName,records[i].lName);
      }
      fclose(errorFile);   //close the file
      printf("Records saved to file: %s\n",fileName);
  }
}

毫无疑问,我可能错误地实现了答案,现在得到一个错误:

error: expected declaration or statement at end of input

在我程序的最后一行找到的

最佳答案

尝试在结构中保存之前需要限制输入的长度。

else {
  char buffer[sizeof (struct Person) * 2];  // twice needed size
  while (fgets(buffer, sizeof buffer, recordFile) != NULL) {
    struct Person P;

    int n;  // Save index where scanning stopped
    int cnt = sscanf(buffer,"%15s%21s %n", P.fName, P.lName, &n);
    if (cnt != 2 || buffer[n] || MaybeAddtionalTests(&P)) {
      SaveBadLine(buffer);
      // do not increment i;
    } else {
      // Good to keep
      // realloc memory as needed here
      records[i] = P;
      i++;
    }
  }
  fclose(recordFile); // close the file

关于c - 将不需要的数据保存到错误文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465092/

相关文章:

c++ - 从远程服务器接收垃圾字符?

javascript - 如何从数组中过滤掉非整数和负数

javascript - JqG​​rid 复选框通过功能启用/禁用

.net - 如何在 VB.NET 中声明嵌套函数?

c++ - 指向字符串和 strcmp 的指针

c++ - 在 macOS 上以编程方式检索崩溃报告

c - C 版和 Fortran90 : optimization for filling subarrays before MPI_Gather

C - 使#define 'return' 成为一个值

c++ - 数组是如何传递的?

c - 双指针 vs 指针数组(**array vs *array[])