簡體   English   中英

C編程:如何打開指定文件並將其內容動態分配到2D數組中?

[英]C programming: how to fopen a designated file and dynamically allocate its contents into a 2D array?

基本上,我的程序會提示用戶輸入要打開的文件的名稱。 我的程序應該打開該文件並將其內容掃描到2D數組中。 但是,您如何做才能使程序打開用戶指定的文件? 到目前為止,這是我的代碼:

#include <stdio.h>
#include <string.h>
FILE *open_file(int ar[3][4]);

int main()
{
  FILE *fp;
  int ar[3][4];

  fp = open_file(ar);
}

FILE *open_file(int ar[3][4])
{
  FILE *fp;
  int i;
  char file[80];
  printf("Please input file name ");
  scanf("%s", &file); //am I supposed to have written ("%s", file) instead?
  fp = fopen("%s", "r");// very confused about this line; will this open the file?
  for (i = 0; i < 12; i++)
    fscanf(fp, "%d", &ar[i][]); //how do you scan the file into a 2D array?
}

要使用malloc,我必須編寫類似fp =(int *)malloc(sizeof(int));?的內容。

scanf("%s", &file); // am I supposed to have written ("%s", file) instead?

是的,但不是出於您想的原因。 所以

scanf("%s", file);

相反,它是正確的(解釋: %s格式說明符告訴scanf()期望使用char * ,但是如果您編寫addressof運算符,並且將printf()類型說明符不匹配,則將其傳遞給char (*)[80]scanf()調用未定義的行為)。

fp = fopen("%s", "r"); // very confused about this line; will this open the file?

不,不會。 它將打開名為%s的文件。 你必須寫

fp = fopen(file, "r");

代替。 不要假設您可以在無法使用的地方使用格式字符串。

varialble file包含用戶輸入的文件名,因此請將其傳遞給fopen。 您所擁有的是格式字符串。

fp = fopen(file, "r");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM