c - 在结构中使用指针并在 C 中写入文件

标签 c pointers struct file-handling

我在用 C 语言做我的大学项目时遇到了一些问题。 我使用了指向结构的指针并使用它来使用 fwrite 写入文件,但它没有帮助。这是我使用的代码。

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>
struct collection{
        char *fname, *lname, *telephone, *address, *seat;   
};

collection * alloc( ){
 struct collection *r = (struct collection *) malloc (sizeof(collection*));
  r->fname = NULL;
  r->lname = NULL;
  r->telephone = NULL;
  r->address = NULL;
  r->seat = NULL;
  return (r);   
}

void string_realloc_and_copy (char **dest, const char *src){
  *dest =(char *) realloc (*dest, strlen (src) + 1);
  strcpy (*dest, src);
}

int main(){
    char ch = 'Y', temp[50];
    FILE *ptf;
    struct collection *asd;
    asd = alloc();

    //printf("%d",sizeof(asd));

    //opening file
    ptf = fopen("lang.txt","w+");
    do{   
    printf("First name: ");
    gets(temp);
    string_realloc_and_copy(&asd->fname,temp);
    printf("Last name: ");
    gets(temp);
    string_realloc_and_copy(&asd->lname,temp);
    printf("Telephone: ");
    gets(temp);
    string_realloc_and_copy(&asd->telephone,temp);
    printf("Address: ");
    gets(temp);
    string_realloc_and_copy(&asd->address,temp);
    printf("Seat you want to book: ");      
    gets(temp);
    string_realloc_and_copy(&asd->seat,temp);
    fwrite(asd,12*sizeof(collection),1,ptf);
    fflush(ptf);
    //fprintf(ptf,"\n");
    printf("Do you wish to enter another data...? (Y/N) ");
    ch = getch();
    }while((ch=toupper(ch))== 'Y');
    rewind(ptf);
        while(fread(asd,12*sizeof(collection),1,ptf) == 1){
        printf("\n\n%s",asd->fname);
        printf("\n\n%s",asd->lname);
        printf("\n\n%s",asd->telephone);
        printf("\n\n%s",asd->address);
        printf("\n\n%s",asd->seat);
    }
    fclose(ptf);    
}

它一直有效,直到到达 asd->telephone 它要求地址并且没有响应。我不知道我做错了什么。我以为是内存不足所以我改了

struct collection *r = (struct collection *) malloc (sizeof(collection*));

struct collection *r = (struct collection *) malloc (12*sizeof(collection*)); 它工作了一段时间,同样的事情又发生了。我正在使用 devC++ 进行编译。提前致谢;

最佳答案

首先,您不应该使用 gets(),因为它已被弃用,而且它从 stdin 获取的字符数没有限制。我建议你使用 fgets。你应该像这样使用 malloc 作为指针

malloc(sizeof(*collection));

这样你就可以为指针分配内存。 还有一件事是用 putc() 尝试这个程序,看看它是否有效。

关于c - 在结构中使用指针并在 C 中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292369/

相关文章:

arrays - 警告 : format ‘%s’ expects type ‘char *’ , 但参数 2 的类型为 ‘char (*)’

c - (linux) "Segmentation fault (core dumped)"将 char 指针传递给 c 中的函数

c++ - std::map 使用比较参数检查第一个和第二个值

c++ - 复杂的 C 声明

c - 与具有超过 500 万个键值对的 REDIS 匹配的最长前缀

c++ - DLL 中的全局指针

c - MATLAB 墨西哥 : retrieving a logical from a struct in MATLAB

c++ - 错误 : expected primary-expression before ')' token (C)

c++ - 标准 C 函数 : Check for -1 or 0?

c - 如何使用从 scanf 获取的参数填充字符指针数组?