2 * Copyright (C) 2008 - 2012 Diego Hernan Borghetti.
24 /* Buffer size for read file. */
27 E_File_Path
*e_file_get_paths(char *file
)
30 char *s
, *pwd
, *slast
;
31 int ndir_rem
, i
, count
, len
;
33 paths
= (E_File_Path
*)malloc(sizeof(E_File_Path
));
36 paths
->lock_file
= NULL
;
40 /* this is a absolute path, nothing to do here,
43 s
= strrchr(file
, '/');
44 paths
->path
= (char *)malloc(s
- file
+ 1);
45 strncpy(paths
->path
, file
, s
- file
);
46 paths
->path
[s
- file
]= '\0';
47 paths
->file
= strdup(file
);
49 else if (!strncmp(file
, "..", 2)) {
50 /* ok, the "hard" case, relative path. */
53 s
= strstr(file
, "..");
54 s
++; /* skip the first. */
64 /* get the current directory. */
67 /* now we need remove ndir_rem from the path. */
70 for (i
= len
-1; i
> 0; i
--) {
73 if (count
== ndir_rem
)
81 slast
+= 2; /* skip ./ */
83 paths
->path
= (char *)malloc(i
+1);
84 strncpy(paths
->path
, pwd
, i
);
86 paths
->file
= (char *)malloc(i
+ strlen(slast
) + 2);
87 strncpy(paths
->file
, pwd
, i
);
88 sprintf(paths
->file
+i
, "/%s", slast
);
92 paths
->path
= strdup(pwd
);
93 paths
->file
= (char *)malloc(strlen(paths
->path
) + strlen(file
) + 2);
94 sprintf(paths
->file
, "%s/%s", paths
->path
, file
);
98 paths
->lock_file
= (char *)malloc(strlen(paths
->file
)+6);
99 sprintf(paths
->lock_file
, "%s.eco~", paths
->file
);
105 int e_file_is_lock(E_File_Path
*paths
)
109 if (stat(paths
->lock_file
, &st
))
110 return(0); /* not locked. */
111 return(1); /* locked. */
114 void e_file_lock(E_File_Path
*paths
)
118 fp
= fopen(paths
->lock_file
, "w");
121 fprintf(fp
, "Eco lock file\n");
126 void e_file_lock_rem(E_File_Path
*paths
)
129 unlink(paths
->lock_file
);
134 E_Buffer
*e_file_read(char *file
, int *status
)
142 /* clean error status. */
145 bf
= e_buffer_new(file
);
149 if (stat(bf
->paths
->file
, &st
)) {
154 if (e_file_is_lock(bf
->paths
)) {
155 /* we already have this file open!! in other session!! */
161 if (!(S_ISREG(st
.st_mode
))) {
162 /* this is not a regular file. */
169 fp
= fopen(bf
->paths
->file
, "r");
171 /* the file exist, but we can't read it. */
178 /* Mark the buffer to avoid auto-complet of
181 bf
->flag
|= BUFFER_NOIDENT
;
185 rb
= fread((void *)&buf
[0], 1, BUF_SIZE
, fp
);
187 e_buffer_insert_str(bf
, &buf
[0], rb
);
188 } while (rb
== BUF_SIZE
);
190 /* always go to the start with new files. */
191 e_buffer_goto_begin(bf
);
193 /* e_buffer_insert/newline mark the buffer with changes,
194 * but in this case we are reading the file, so unmark
197 BUFFER_UNSET(bf
, BUFFER_FLUSH
);
199 /* and lock the file. */
200 e_file_lock(bf
->paths
);
202 /* Remove the mark. */
203 bf
->flag
&= ~BUFFER_NOIDENT
;
209 void e_file_write(E_Eco
*ec
, E_Buffer
*bf
)
215 if (!(bf
->flag
& BUFFER_FLUSH
))
218 fp
= fopen(bf
->paths
->file
, "w");
225 for (i
= 0; i
< ln
->used
; i
++)
226 fputc(ln
->text
[i
], fp
);
235 BUFFER_UNSET(bf
, BUFFER_FLUSH
);
237 e_status_set_msg(ec
, "(Wrote %d lines)", nlines
);