这是我的问题:我在字符串矩阵中保存了一些相对路径。根据用户选择,我必须打开某个文件。问题是,当我使用fopen函数时,文件指针不指向任何东西。以下是代码示例:
#include <stdio.h>
#include <stdlib.h>
#define MAX_PATH 100
///Global matrix of strings, containing the paths used in fopen() function
char paths[MAX_PATH][3] = {{"c:\\Users\\ThisPc\\Desktop\\file1.txt"},
{"c:\\Users\\ThisPc\\Desktop\\file2.txt"},
{"c:\\Users\\ThisPc\\Desktop\\file3.txt"}};
int main(){
///Declaring and initializing the 3 file pointers to NULL
FILE *filepntr1 = NULL;
FILE *filepntr2 = NULL;
FILE *filepntr3 = NULL;
///Opening the 3 files with the correct arrays
filepntr1 = fopen(paths[1], "w");
filepntr2 = fopen(paths[2], "w");
filepntr3 = fopen(paths[3], "w");
///Typing something on the files opened, just to check if the files where really opened
fprintf(filepntr1, "hello");
fprintf(filepntr2, "hello");
fprintf(filepntr3, "hello");
///Closing the files
fclose(filepntr1);
fclose(filepntr2);
fclose(filepntr3);
return 0;
}
显然,这三个文件仍为空白。
我做错了什么?
答案 0 :(得分:5)
您错误地创建并填充路径数组的主要问题,请尝试此方法,例如:
select it.id,nt1.name,nt2.name,nt3.name,nt4.name
from it
join nt nt1
on nt1.uid=it.pa1
join nt nt2
on nt2.uid=it.pa2
join nt nt3
on nt3.uid=it.pa3
join nt nt4
on nt4.uid=it.pa4
order by it.id;
+------+------+------+--------+------+
| id | name | name | name | name |
+------+------+------+--------+------+
| 4800 | sim | tim | Cadman | bim |
| 4801 | curt | lert | qbert | kim |
+------+------+------+--------+------+
2 rows in set (0.00 sec)
数组索引从0开始的第二个问题:
const char* paths[3] = {"c:\\Users\\ThisPc\\Desktop\\file1.txt",
"c:\\Users\\ThisPc\\Desktop\\file2.txt",
"c:\\Users\\ThisPc\\Desktop\\file3.txt"};
答案 1 :(得分:1)
您应该检查fopen
,fprintf
,fclose
的所有失败(失败时,请考虑使用perror
)。你可能想打电话(有时候)fflush
。
请务必阅读我在此提及的每项功能的文档。
顺便说一下,你可以生成一些文件路径,例如
char path[384];
int i = somenumber();
snprintf(path, sizeof(path), "/some/path/data_%d.txt", i);
FILE *f = fopen(path, "r");
if (!f) { perror(path); exit(EXIT_FAILURE); };
答案 2 :(得分:0)
你想为你的路径声明一个二维数组吗?看起来您将整个第一行(三个字符串)传递给fopen()
。