[英]Writing to a file using fprintf in c
我正在嘗試在我的程序中寫入文件,但我不確定我哪里出錯了。
我可能錯誤地使用了fscanf
,這很有可能。
我需要將未解決的難題寫入文件,以查看是否將文件正確放入我的代碼中,但就像我說的那樣,我不確定我是否正確使用了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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.