【问题标题】:How to write to a textfile in c (with the intended functionality)如何在 c 中写入文本文件(具有预期功能)
【发布时间】:2014-04-21 19:52:40
【问题描述】:

我正在尝试学习编写数据(字符、整数和字符串)的语法。我研究了以下链接http://web.cs.swarthmore.edu/~newhall/unixhelp/C_files.html的内容,编写了如下代码。该代码的目的是以下列方式将数据存储在文本文件中:

33
你好

15
好的

如果我输入 33、Hello、15、Ok 和 0。但是当我在运行程序后打开它时,文本文件完全是空白的。 这里有没有人擅长将数据存储在文本文档中,可以给我一些提示我做错了什么?或者,如果有任何其他你知道的好教程?

我的测试代码附在下面[我可以毫无问题地编译和运行它,只是它没有做我期望的事情:( ]

char stdin_buff[20];
int stdin_int;
FILE *fp;
char *filename = "data.txt"; //name of the textfile where the data should be stored 

void handle_String_input(char msg[]){
    fp = fopen(filename, "w"); //opens the text file in write mode
    if(fp==NULL){
        printf("Unable to open the file! \n");
    }
    fseek(fp, 1, SEEK_END); //seek the end of the text file
    fputs(msg,fp); //writes the message to the text file
    putc('\n',fp); //new line in the text document
    putc('\n',fp); //new line in the text document 
    fclose(fp); //closes the text file
}

void handle_Integer_input(int nbr){
    fp = fopen(filename, "w"); //opens the text file in write mode
    if(fp==NULL){
        printf("Unable to open the file! \n");
    }
    fseek(fp, 1, SEEK_END); //seek the end of the text file
    fputc(nbr,fp); //writes the nbr into the text file 
    putc('\n',fp); //new line in the text document 
    fclose(fp); //closes the text file
}

void main(){
    while(1){
        memset(stdin_buff,'\0',10); //clears the content of stdin_buff 
        printf("Enter an integer(enter 0 to exit): ");
        fgets(stdin_buff,9,stdin); //retrieves an input from keyboard(the user is expected to only use the numbers 0-9)
        stdin_int=atoi(stdin_buff);
        handle_Integer_input(stdin_int);
        if(stdin_int==0){
            break;
        }
        memset(stdin_buff,'\0',10); //clears the content of stdin_buff 
        printf("Enter a string(enter 0 to exit): ");
        fgets(stdin_buff,9,stdin); //retrieves input from keyboard
        handle_String_input(stdin_buff);
        if(stdin_buff[0]=='0'){
            break;
        }
    }
}

我错过/不明白什么?任何有关改进的建议表示赞赏!

【问题讨论】:

  • 您可能对 JSONYAML 等文本格式以及实现它们的库(如 jansson 等)感兴趣。您还应该调查lexingparsing 技术。
  • @Jongware:我看不出这个问题和 MPI 之间有直接的关系......
  • "您反复打开输出文件以进行写入。默认情况下,这会将其截断为 0 字节。"

标签: c text text-files


【解决方案1】:

在 fopen 语句中,使用“a”(用于追加)而不是“w”。 “w”clears the file.

目前,如果您通过输入整数“0”结束交互式会话,则文件将显示为空。如果你以字符串 '0' 结尾,你应该只看到字符 0。

【讨论】:

  • 另外,将整数 1 写入此文件不会使其包含 line "1\n"。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多