424

C で書かれたアプリケーションで開いたファイルのサイズを調べるにはどうすればよいですか? ロードしたファイルの内容を文字列に入れたいので、サイズを知りたいですmalloc()。ただ書くことmalloc(10000*sizeof(char));は私見では悪い考えです。

4

8 に答える 8

584

ファイルの最後までシークしてから、位置を尋ねる必要があります。

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

その後、次のようにシークバックできます。

fseek(fp, 0L, SEEK_SET);

または(最初に行きたい場合)

rewind(fp);
于 2008-10-26T20:57:29.897 に答える
410

標準ライブラリの使用:

実装がSEEK_ENDを有意義にサポートしていると仮定します。

fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file

Linux / POSIX:

stat(ファイル名がわかっている場合)、またはfstat(ファイル記述子がある場合)を使用できます。

statの例を次に示します。

#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;

Win32:

GetFileSizeまたはGetFileSizeExを使用できます。

于 2008-10-26T20:59:32.153 に答える
120

ファイル記述子がある場合fstat()は、ファイルサイズを含む統計構造を返します。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.
struct stat buf;
fstat(fd, &buf);
off_t size = buf.st_size;
于 2008-10-26T21:17:18.017 に答える
22

私は短くて甘いfsize関数を作っただけです(注、エラーチェックはありません)

int fsize(FILE *fp){
    int prev=ftell(fp);
    fseek(fp, 0L, SEEK_END);
    int sz=ftell(fp);
    fseek(fp,prev,SEEK_SET); //go back to where we were
    return sz;
}

/dev/null標準 C ライブラリにそのような関数がないのはちょっとばかげていますが、すべての「ファイル」にサイズがあるわけではないので (たとえば) 、なぜ難しいのかがわかります。

于 2011-03-27T02:09:48.093 に答える
17

lseek / fseek / stat / fstatを使用してファイルサイズを取得する方法は?

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

void
fseek_filesize(const char *filename)
{
    FILE *fp = NULL;
    long off;

    fp = fopen(filename, "r");
    if (fp == NULL)
    {
        printf("failed to fopen %s\n", filename);
        exit(EXIT_FAILURE);
    }

    if (fseek(fp, 0, SEEK_END) == -1)
    {
        printf("failed to fseek %s\n", filename);
        exit(EXIT_FAILURE);
    }

    off = ftell(fp);
    if (off == -1)
    {
        printf("failed to ftell %s\n", filename);
        exit(EXIT_FAILURE);
    }

    printf("[*] fseek_filesize - file: %s, size: %ld\n", filename, off);

    if (fclose(fp) != 0)
    {
        printf("failed to fclose %s\n", filename);
        exit(EXIT_FAILURE);
    }
}

void
fstat_filesize(const char *filename)
{
    int fd;
    struct stat statbuf;

    fd = open(filename, O_RDONLY, S_IRUSR | S_IRGRP);
    if (fd == -1)
    {
        printf("failed to open %s\n", filename);
        exit(EXIT_FAILURE);
    }

    if (fstat(fd, &statbuf) == -1)
    {
        printf("failed to fstat %s\n", filename);
        exit(EXIT_FAILURE);
    }

    printf("[*] fstat_filesize - file: %s, size: %lld\n", filename, statbuf.st_size);

    if (close(fd) == -1)
    {
        printf("failed to fclose %s\n", filename);
        exit(EXIT_FAILURE);
    }
}

void
stat_filesize(const char *filename)
{
    struct stat statbuf;

    if (stat(filename, &statbuf) == -1)
    {
        printf("failed to stat %s\n", filename);
        exit(EXIT_FAILURE);
    }

    printf("[*] stat_filesize - file: %s, size: %lld\n", filename, statbuf.st_size);

}

void
seek_filesize(const char *filename)
{
    int fd;
    off_t off;

    if (filename == NULL)
    {
        printf("invalid filename\n");
        exit(EXIT_FAILURE);
    }

    fd = open(filename, O_RDONLY, S_IRUSR | S_IRGRP);
    if (fd == -1)
    {
        printf("failed to open %s\n", filename);
        exit(EXIT_FAILURE);
    }

    off = lseek(fd, 0, SEEK_END);
    if (off == -1)
    {
        printf("failed to lseek %s\n", filename);
        exit(EXIT_FAILURE);
    }

    printf("[*] seek_filesize - file: %s, size: %lld\n", filename, (long long) off);

    if (close(fd) == -1)
    {
        printf("failed to close %s\n", filename);
        exit(EXIT_FAILURE);
    }
}

int
main(int argc, const char *argv[])
{
    int i;

    if (argc < 2)
    {
        printf("%s <file1> <file2>...\n", argv[0]);
        exit(0);
    }

    for(i = 1; i < argc; i++)
    {
        seek_filesize(argv[i]);
        stat_filesize(argv[i]);
        fstat_filesize(argv[i]);
        fseek_filesize(argv[i]);
    }

    return 0;
}
于 2010-01-05T02:36:01.360 に答える
9

ファイルサイズを計算せず、必要に応じて配列を拡大することを検討しましたか? 以下に例を示します (エラー チェックは省略されています)。

#define CHUNK 1024

/* Read the contents of a file into a buffer.  Return the size of the file 
 * and set buf to point to a buffer allocated with malloc that contains  
 * the file contents.
 */
int read_file(FILE *fp, char **buf) 
{
  int n, np;
  char *b, *b2;

  n = CHUNK;
  np = n;
  b = malloc(sizeof(char)*n);
  while ((r = fread(b, sizeof(char), CHUNK, fp)) > 0) {
    n += r;
    if (np - n < CHUNK) { 
      np *= 2;                      // buffer is too small, the next read could overflow!
      b2 = malloc(np*sizeof(char));
      memcpy(b2, b, n * sizeof(char));
      free(b);
      b = b2;
    }
  }
  *buf = b;
  return n;
}

これには、ファイル サイズを取得できないストリーム (stdin など) でも機能するという利点があります。

于 2009-10-29T13:38:45.027 に答える
8

Linuxを使用している場合は、glibのg_file_get_contents関数を使用することを真剣に検討してください。ファイルのロード、メモリの割り当て、およびエラーの処理のためのすべてのコードを処理します。

于 2008-10-26T21:13:54.043 に答える
-42
#include <stdio.h>

#define MAXNUMBER 1024

int main()
{
    int i;
    char a[MAXNUMBER];

    FILE *fp = popen("du -b  /bin/bash", "r");

    while((a[i++] = getc(fp))!= 9)
        ;

    a[i] ='\0';

    printf(" a is %s\n", a);

    pclose(fp);
    return 0;
}  

HTH

于 2008-10-29T13:50:48.337 に答える