开发者

Dynamic fopen filepath in C

开发者 https://www.devze.com 2023-02-09 06:46 出处:网络
char filePath[200]; printf(\"Enter filepath: \\n\"); fgets(filePath, 200, stdin); f = fopen(filePath, \"r\");
char filePath[200];   
printf("Enter filepath: \n");
fgets(filePath, 200, stdin);
f = fopen(filePath, "r");   

while(!feof(f)) // crashed on this line
{

}

I cannot for some reason get this to work. Please could some one point out what I am doing wrong on this.

Could you ad开发者_如何学JAVAvice the correct way to write code for opening a filepath specified by user through command prompt?

Thanks, Freddy


fopen(3) returns NULL if it cannot open the file. You should always check for that. fgets(3) does that too, but your problem is probably the new-line character that it keeps in the returned string.


fgets puts endline to the end of string (\r\n in Windows). So your filePath contains garbage at the end and file of that name doesn't exist. I would recommend to use scanf("%[^\r\n]s", filePath) instead. (scanf may differ on some implementations, please read your documentation.)

update: You should also ensure there won't be a buffer overflow by specifying buffer size. For example this way:

char filePath[100];
scanf("%99[^\r\n]s", filePath);


Try something like:

size_t l = strlen(filePath);
if (filePath[l-1] == '\n') filePath[--l-1] = 0;
if (filePath[l-1] == '\r') filePath[--l-1] = 0;


You check the error code from fgets and fopen. Both return null if they failed

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号