gpt4 book ai didi

c - 在c中使用fprintf写入文件

转载 作者:行者123 更新时间:2023-11-30 20:58:22 25 4
gpt4 key购买 nike

我正在尝试写入程序中的文件,但我不确定哪里出错了。

我可能错误地使用了fscanf,这是很有可能的。

我需要将 Unresolved 难题写入文件,以查看是否正确地将文件放入我的代码中,但就像所说的那样,我不确定我是否使用了fscanf正确。 (谜题文件在我的 Clionfile 中,我知道这不是问题。)

这是我用于阅读的程序部分。

int read(const char *name, int **problem, int **z, int *size) {
int n;
int *p;
int *c;
FILE* input;

input = fopen("name", "r");
fscanf(input,"%d", &n);

*size = n;
p = (int *)malloc(n * n * sizeof(int)); /* nxn grid has n*n elements*/
c = (int *)malloc(n * n * sizeof(int));
*problem = p;
*z = c;

input = fopen(name, "r");
fprintf(input, "%d\n", n);
fclose(input);
return 0;
}

我需要知道的是我哪里出了问题,或者我的问题是否与此有关。

最佳答案

我确实没有完全遵循你的代码,但创建了一个可以编译和运行的版本。我添加了几个断言来显示我期望的值。我发现这些有助于确认我期望程序执行的操作。

#include <stdio.h>
#include <stdlib.h>
#include <itclInt.h>
#include <assert.h>


int ReadFile(const char *name, int **problem, int **z, int *size) {
int n;
int *p;
int *c;
FILE *input;
FILE *output;

/* Open file "name" for reading and writing */
output = fopen(name, "w");
assert(output != NULL);

fprintf(output, "%d", *size);
if(fclose(output) == EOF)
perror ("fclose-input");

/* Open file "name" for reading and writing */
input = fopen(name, "r");
assert(input != NULL);

/* Get integer input from the file and store it in n. */
fscanf(input, "%d", &n);
assert(n == *size);
if(fclose(input) == EOF)
perror ("fclose-input");

p = malloc(n * n * sizeof(int)); /* nxn grid has n*n elements*/
c = malloc(n * n * sizeof(int));
*problem = p;
*z = c;

input=fopen(name,"w");
fprintf(input,"%d\n",n);
if(fclose(input) == EOF)
perror ("fclose-input");
return 0 ;

}


int main() {
int size = 5;
int* problemIntPtr;
int* zintPtr;

ReadFile("name.txt", &problemIntPtr, &zintPtr, &size);
printf("We made it!\n");
return 0;
}

关于c - 在c中使用fprintf写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com