【问题标题】:I can't write a file我不能写文件
【发布时间】:2015-07-17 14:38:54
【问题描述】:

我第一次尝试用 C 语言编写文件,但我明白了,但我不知道为什么。变量nombre是我创建的文件的名称,然后我想在这个文件中写入字符串testo的内容但是总是报错:

process return -1073741819

char* inserisci (char*);

int main() {
    char *nombre=NULL,letra;
    char*testo=NULL;

    int i=0;
    printf("Type file name: ");
    nombre=malloc(sizeof(char));
    letra=getche();
    *(nombre+i)=letra;
    while(letra!='\r'){
        i++;
        nombre=realloc(nombre,(i+1)*sizeof(char));
        letra=getche();
        *(nombre+i)=letra;
    }
    *(nombre+i)='\0';
    printf("\n");
    testo=inserisci(testo);
    fopen(nombre,"w+");
    fprintf(nombre,"%s",testo);
    return 0;
}

char* inserisci (char* testo){
    char letra;
    int i=0;
    testo=malloc(sizeof(char));
    letra=getche();
    *(testo+i)=letra;
    while(letra!='\r'){
        i++;
        testo=realloc(testo,(i+1)*sizeof(char));
        letra=getche();
        *(testo+i)=letra;
    }
    *(testo+i)='\0';
    return testo;
}

【问题讨论】:

  • 这个错误是...?
  • 你的fprintf用法不对,需要把指向文件的指针作为第一个参数,而不是文件名本身。
  • 与您的问题无关,但使用 realloc 重新分配每个字节的字节确实是个坏主意。
  • 它的效率非常低,而且任何调用都可能失败,而您没有对其进行测试,因此可能会使您的程序崩溃。
  • Hm best 可能是一个见仁见智的问题,但一种常见且有用的模式:1.) 分配一个足够大的缓冲区以容纳您认为对数据合理的内容2.) 在变量中跟踪缓冲区使用情况 3.) 每次缓冲区已满时,将大小加倍并使用 realloc。请参阅this example,我使用此策略读取文件。

标签: c file dynamic printf


【解决方案1】:
 fprintf(nombre,"%s",testo);
            ^here file pointer is needed not the char pointer containing files path or name.

声明一个文件指针

         FILE *fp;
         fp=fopen(nombre,"w+');
         fprintf(fp,"%s",testo); 

这是fprintf的格式

      int fprintf(FILE *stream, const char *format, ...)

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 2015-02-23
    • 2020-01-20
    • 2015-01-17
    • 1970-01-01
    • 2010-10-05
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多