我製作了第一個C程序。它刪除C註釋('//')。我將一個字符串傳遞給函數strip_comments,創建一個與參數字符串大小相同的新字符串,然後我做一個拷貝,char by char,忽略註釋。C - 我不想分配我不會使用的內存! (newby question)
這是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define IN 1
#define OUT 0
int file_size(FILE *file);
char * strip_comments(char *content);
int main(int argc, char *argv[])
{
FILE *file;
char *buffer, *content;
int size;
if (argc == 1)
{
printf("USAGE: stripccomments filename\n");
return 1;
}
if ((file = fopen(argv[1], "rw")) == NULL)
{
printf("Could not open file '%s'.\n", argv[1]);
return 1;
}
size = file_size(file);
buffer = malloc(sizeof(char) * size);
if (buffer == NULL)
{
printf("Could not allocate memory\n");
return 1;
}
fread(buffer, sizeof(char), size, file);
content = strip_comments(buffer);
printf("%s", content);
free(buffer);
fclose(file);
return 0;
}
int file_size(FILE *file)
{
int size;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
return size;
}
char * strip_comments(char *content)
{
int state, length, i, j;
char *new_content;
state = OUT;
length = strlen(content);
new_content = malloc(sizeof(char) * length);
j = 0;
for (i = 0; i < length; i++)
{
if (content[i] == '/' && content[i + 1] == '/')
{
state = IN;
i++;
continue;
}
if (state && content[i] == '\n')
{
state = OUT;
}
if (!state)
{
new_content[j] = content[i];
j++;
}
}
new_content[j + 1] = '\0';
return new_content;
}
如果有一些意見,我將只使用分配的字符串的一些字節。我不想分配超過我將使用。什麼是最好的方法來做到這一點,並返回一個新的字符串?或者我應該修改作爲參數傳遞的字符串?
更新:這個未使用的空間會發生什麼?它是否仍然處於「僵局」?當執行到最後時,這個空間會發生什麼?
謝謝。
不要阻止你,但剝離C中的註釋要比這更復雜一點。想象一下你的代碼如何迴應這種情況:'char * string =「this is a // string」;' – 2011-05-19 20:15:14
刪除'sizeof(char)'。它只是顯示代碼的作者不知道C. – 2011-05-19 20:19:23
所以,有一個錯誤:) – thom 2011-05-19 20:19:40