将字符串从指针复制到字符串 [英] Copying a string from a pointer to a string

查看:29
本文介绍了将字符串从指针复制到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一些代码,它从 sd 卡(使用 FatFs)读取文件名并将它们显示到屏幕上.这是我工作的一个片段,这会按预期打印出卡上的文件 -

I'm developing some code which reads file names from an sd-card (using FatFs) and displays them to the screen. Here's a snipet of what I have working, this prints out the files on the card as expected -

FRESULT result;
        char *path = '/'; //look in root of sd card
        result = f_opendir(&directory, path);   //open directory
        if(result==FR_OK){
            for(;;){
                result = f_readdir(&directory, &fileInfo); //read directory
                if(result==FR_OK){
                    if(fileInfo.fname[0]==0){ //end of dir reached
                        //LCD_UsrLog("End of directory.
");
                        break;
                    }
                    if(fileInfo.fname[0]=='.')continue; //ignore '.' files

                    TCHAR *fn_ptr; //file name, why a pointer?
                    fn_ptr=&fileInfo.fname; //get file name            
                    LCD_UsrLog("%s
",fn_ptr);
                    for(delay=0;delay<0x0FFFFF;delay++){ShortDelay();} //delay to display

                }//end result==fr_ok
            }//end for
        }//end result==fr_ok

在哪里

typedef char TCHAR

typedef struct {
DWORD   fsize;          /* File size */
WORD    fdate;          /* Last modified date */
WORD    ftime;          /* Last modified time */
BYTE    fattrib;        /* Attribute */
TCHAR   fname[13];      /* Short file name (8.3 format) */

} FILINFO;

我需要将文件名复制到数组中进行处理,但是我尝试了几种方法,但似乎无法使数组正常工作.我尝试创建一个任意大的 TCHAR 数组并取消引用文件名指针,但这会打印垃圾.

I need to copy the names of the files into an array for processing however I've tried a few ways but can't seem to get the array working. I have tried creating an arbitrarily large array of TCHARs and dereferencing the file name pointer but this prints garbage.

FRESULT result;
        char *path = '/'; //look in root of sd card
        TCHAR fileList[50];
        u32 index=0;
        result = f_opendir(&directory, path);   //open directory
        if(result==FR_OK){
            for(;;){
                result = f_readdir(&directory, &fileInfo); //read directory
                if(result==FR_OK){
                    if(fileInfo.fname[0]==0){ //end of dir reached
                        //LCD_UsrLog("End of directory.
");
                        break;
                    }
                    if(fileInfo.fname[0]=='.')continue; //ignore '.' files

                    TCHAR *fn_ptr; //file name, why a pointer?
                    fn_ptr=&fileInfo.fname; //get file name            

                    fileList[index]=*fn_ptr;
                    LCD_UsrLog("%s
",fileList[index]);
                    for(delay=0;delay<0x0FFFFF;delay++){ShortDelay();} //delay to display
                    index++;
                }//end result==fr_ok
            }//end for
        }//end result==fr_ok

我怀疑这是一个关于指针或正确使用字符数组的简单错误,但自从我上次接触 C 以来已经 4 年多了,我迷路了!

I suspect this is a simple mistake regarding pointers or the proper usage of an array of chars but it has been 4+ years since I've last touched C and I'm lost!

任何帮助将不胜感激.

推荐答案

第一个问题:目前你的文件列表是一个字符数组,而它应该是一个字符串数组.所以声明为

First problem: currently your file list is an array of chars, while it should be an array of strings. So declare it as

TCHAR* fileList[50];

然后为每个文件名分配适当长度的字符串(不要忘记终止 0 字符的额外空间).您还需要将文件名显式复制到您的名称列表中,因为 fileInfo 的内容在每个循环周期中都会被覆盖,因此简单地存储指针将导致您的列表包含最后一个文件的名称 50次.

then allocate the strings of proper length for each filename (not forgetting the extra space for the terminating 0 char). You also need to explicitly copy the filenames into your name list, because the contents of fileInfo get overwritten in each loop cycle, so simply storing the pointers would result in your list containing the name of the last file 50 times.

总而言之,你需要这样的东西:

All in all, you need something like this:

                if(fileInfo.fname[0]=='.')continue; //ignore '.' files

                fileList[index] = malloc(strlen(fileInfo.fname) + 1);
                strcpy(fileList[index], fileInfo.fname);

                LCD_UsrLog("%s
",fileList[index]);

(免责声明:不保证它会按原样工作,我没有机会测试它,但希望这能给你带来想法).

(Disclaimer: No guarantee that this works as it is, I have no chance to test it, but hopefully this gives you the idea).

或者,如果你知道文件名长度的上限,你可以声明一个固定长度的文件名数组,摆脱动态分配.但是为了安全起见,您应该使用 strncpy 而不是 strcpy 以防止缓冲区溢出.而且这还需要附加终止字符 0,这也是为了安全起见:

Alternatively, if you know the upper limit of the filename length, you can declare an array of filenames with fixed length, and get rid of dynamic allocation. But then you should use strncpy instead of strcpy to be on the safe side, to prevent buffer overflows. And this also requires the terminating 0 character to be appended, again to be on the safe side:

TCHAR fileList[50][MAX_FILENAME_LENGTH + 1];

...
strncpy(fileList[index], fileInfo.fname, strlen(fileInfo.fname));
fileList[index][MAX_FILENAME_LENGTH] = '';

这篇关于将字符串从指针复制到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆