搜索和写入txt文件C

时间:2017-08-29 01:10:42

标签: c

我需要帮助:/该程序应该在txt文件中查找文本,如果有该文本,则生成另一个文本。 例如:

我随机生成 插入ALUM_PROF VALUES(2,4); 如果找到这个文本,我会查看txt,如果不是,那么我将其写入txt。

然后它生成 插入ALUM_PROF VALUES(5,7); 我在txt中查找它,如果不是,我将它写在txt

然后它生成 插入ALUM_PROF VALUES(2,4); 我在txt中查找它,因为它在,然后我不写它,我再生成另一个。

int NUMEROS_AL_PROFE();
#define fila 100 

int main()
{
    char aux[200];
    char aux2[200];
    int contador=0;
    FILE *f;
    f = fopen("prueba.txt","a+"); 
    if(f==NULL)
    {
        printf("no se ha podido abrir el archivo");
        exit(1);
    }

    int i,num_prof,num_alum=1;

    num_prof = NUMEROS_AL_PROFE();
    fprintf(f,"INSERT INTO ALUM_PROF VALUES (%d,%d);\n",num_alum,num_prof); //escribo en el fichero f
    num_alum++;

    for(i=0;i<fila;i++)
    {
        num_prof = NUMEROS_AL_PROFE();
        sprintf(aux,"INSERT INTO ALUM_PROF VALUES (%d,%d);\n",num_alum,num_prof); //almaceno el valor en aux

        while(!feof(f))
        {
            fgets(aux2,200,f); //I read from the file f and I keep each line in aux2

            if(strcmp(aux,aux2) == 0 ) //If a1 and a2 are equal then it is repeated.
            {
                contador=1;
            }
            memset(aux2, '\0',200);  //Vacio el array aux2
        }
        memset(aux, '\0',200);
        if(contador==0)
        {
            fprintf(f,"INSERT INTO ALUM_PROF VALUES (%d,%d);\n",num_alum,num_prof);
        }

        num_alum++;
    }
    fclose(f);
}
//Random Number
int NUMEROS_AL_PROFE()
{
    int num;
    num = rand() % 17 + 1; //Numeros aleatorios entre 1 y 17
    num = num + 1; 
    return num;
}

程序编译,当它运行时它仍然加载,它根本不写任何东西并生成一个重txt。

1 个答案:

答案 0 :(得分:1)

您需要重置文件的阅读位置和contador标志。

修复代码示例:

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

#define fila 100

int NUMEROS_AL_PROFE(void);

int main(void){
    char aux[200];
    char aux2[200];
    int contador=0;
    FILE *f  = fopen("prueba.txt","a+"); 

    if(f==NULL) {
        printf("no se ha podido abrir el archivo");
        exit(1);
    }

    int num_alum = 1;

    srand(time(NULL));//Change seed of random number
    for(int i = 0; i < fila; i++){
        sprintf(aux,"INSERT INTO ALUM_PROF VALUES (%d,%d);\n", num_alum++, NUMEROS_AL_PROFE());

        rewind(f);//The file reading position is set to the beginning.
        contador = 0;//reset flag
        while(fgets(aux2, sizeof aux2, f)){//while(!feof(f)) has a problem. It has already been pointed out by stackptr's comment.
            if(strcmp(aux, aux2) == 0 ){
                //fprintf(stderr, "DEBUG:already exist %s", aux);
                contador = 1;
                break;
            }
        }
        if(contador == 0){
            //fprintf(stderr, "DEBUG:write %s", aux);
            fputs(aux, f);
        }
    }
    fclose(f);
}

int NUMEROS_AL_PROFE(void){
    int num;
    num = rand() % 17 + 1;
    num = num + 1; 
    return num;
}