【发布时间】:2010-03-19 02:51:29
【问题描述】:
我正在编写一个将数据从文件传递到数组的程序,但是我在使用 fopen() 时遇到了问题。当我将文件路径硬编码到参数中(例如fopen ("data/1.dat", "r");)时,它似乎工作正常,但是当我将它作为指针传递时,它返回NULL。
请注意,如果从命令行输入,第 142 行将打印“data/1.dat”,因此 parse_args () 似乎正在工作。
132 int
133 main(int argc, char **argv)
134 {
135 FILE *in_file;
136 int *nextItem = (int *) malloc (sizeof (int));
137 set_t *dictionary;
138
139 /* Parse Arguments */
140 clo_t *iopts = parse_args(argc, argv);
141
142 printf ("INPUT FILE: %s.\n", iopts->input_file); /* This prints correct path */
143 /* Initialise dictionary */
144 dictionary = set_create (SET_INITAL_SIZE);
145
146 /* Use fscanf to read all data values into new set_t */
147 if ((in_file = fopen (iopts->input_file, "r")) == NULL)
148 {
149 printf ("File not found...\n");
150 return 0;
151 }
谢谢! 里斯
更多:如果我在运行 set_create() (ln 144) 后尝试打印字符串,则不会打印字符串。 (但函数中根本没有对字符串的任何引用......)
47 set_t *
48 set_create(int size)
49 {
50 set_t *set;
51
52 /* set set_t members */
53 set->items = 0;
54 set->n_max = size;
55 set->lock = FALSE;
56
57 /* allocate memory for dictionary input */
58 set->data = (int *) malloc (size * sizeof (int));
59
60 return set;
61 }
如果我在 fopen() 之后调用这个函数,它确实有效。 我看不出这对文件名有何影响...
再次感谢。
【问题讨论】:
-
您是否检查过第 144 行没有以某种方式破坏名称?
-
在 input_file 末尾嵌入空格、空值、换行符或其他任何看起来打印正确但会使 fopen barf 的内容?
-
为了解决 Duck 的问题,我总是在
'中附上类似的测试打印。喜欢printf("Filename '%s'\n",p->name);。 -
尝试在 fopen 失败后再次打印路径..这将排除破坏(见某事的答案)。还可以尝试在 fopen 之后移动 set_create 函数调用(虽然如果这可行,它不是解决方案)。
-
从我们现有的信息来看,这段代码应该可以正常工作。我们缺少什么?试着提炼出所有不相关的东西,你会找到罪魁祸首。
标签: c char fopen pass-by-reference